接上一節
@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是在方法執行之后執行。
