springtboot缓存之@CacheEvict

时间:2022-07-23
本文章向大家介绍springtboot缓存之@CacheEvict,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

接上一节

@CacheEvict:缓存清除。

应用场景:我们删除了数据库中的数据之后,将缓存也进行删除。

package com.gong.springbootcache.controller;

import com.gong.springbootcache.bean.Employee;
import com.gong.springbootcache.service.EmployeeService;
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.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //value:指定缓存的名字,每个缓存组件有一个唯一的名字。缓存组件由CacheManager进行管理。
    //key:缓存数据时用到的key,默认使用方法参数的值,1-方法返回值 key =
    //#id也可这么表示:#root.args[0](第一个参数)
    //keyGenerator:指定生成缓存的组件id,使用key或keyGenerator其中一个即可
    //cacheManager,cacheResolver:指定交由哪个缓存管理器,使用其中一个参数即可
    //condition:指定符合条件时才进行缓存
    //unless:当unless指定的条件为true,方法的返回值就不会被缓存
    //sync:是否使用异步模式
    //"#root.methodName+'[+#id+]'"
    @Cacheable(value = "emp")
    @ResponseBody
    @RequestMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        Employee emp = employeeService.getEmp(id);
        return emp;
    }

    @CachePut(value = "emp",key="#employee.id")
    @ResponseBody
    @GetMapping("/emp")
    public Employee updateEmp(Employee employee){
        Employee emp =  employeeService.updateEmp(employee);
        return emp;
    }

    @CacheEvict(value = "emp",key = "#id")
    @ResponseBody
    @GetMapping("/emp/del/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeService.deleteEmp(id);
        return "删除成功";
    }
}

首先也是查询两次:

第一次发送sql请求,第二次直接从缓存中获取。

然后我们进行删除:

最后再进行一次查询:

查询不到数据,然后我们看控制台:

说明了:缓存中没数据了,同时数据库中的数据也被删除了。

@CacheEvict还有个allEntries属性,默认为false,我们可以将其设置为,清除指定缓存中的所有缓存,这里是emp。

@CacheEvict还有个beforeInvocation属性,默认为false,表示缓存是否在方法执行之前进行清除。默认为false是在方法执行之后执行。