当前位置: 首页 > 工具软件 > xxl-cache > 使用案例 >

【缓存】@CacheEvict

浦毅
2023-12-01

@CacheEvict

功能:缓存清除。

示例:
【缓存】@CachePut的基础上进行修改:
EmployeeService类:

package com.qublog.cache.service;

import com.qublog.cache.bean.Employee;
import com.qublog.cache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    //将方法的运行结果进行缓存,以后再要相同数据,直接从缓存中获取,不用调用方法
    @Cacheable(cacheNames = {"emp"})
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    //key也可以使用#result.id
    @CachePut(value = "emp",key = "#employee.id")
    public Employee updateEmp(Employee employee) {
        employeeMapper.updateEmp(employee);
        System.out.println("更新"+employee);
        return employee;
    }

    //用key来指定要清除的数据
    @CacheEvict(value = "emp",key = "#id")
    public void deleteEmp(Integer id) {
        System.out.println("删除"+id);
        //employeeMapper.deleteEmp(id);
    }

}

EmployeeController类:

package com.qublog.cache.controller;

import com.qublog.cache.bean.Employee;
import com.qublog.cache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @GetMapping("/emp/{id}")
    public Employee getEmployee(@PathVariable("id") Integer id) {
        Employee emp = employeeService.getEmp(id);
        return emp;
    }

    @GetMapping("/emp")
    public Employee updateEmp(Employee employee) {
        Employee emp = employeeService.updateEmp(employee);
        return emp;
    }

    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeService.deleteEmp(id);
        return "success";
    }
}

进行测试先访问http://localhost:8080/emp/1,再http://localhost:8080/delemp/1删除key指定的缓存,再访问http://localhost:8080/emp/1,发现缓存已删除,需要再次访问数据库。

可以使用allEntries属性将这个缓存中的数据都删除。

beforeInvocation属性:缓存的清除是否在方法之前执行,默认代表在方法执行之后执行。beforeInvocation=true代表清除缓存是在方法运行之前执行,无论方法是否出现异常,缓存都清除。

 类似资料: