开发者学堂课程【SpringBoot 快速掌握 - 高级应用:@ CacheEvict】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/613/detail/9293
@ CacheEvict
@CacheEvict :缓存清除
key:指定要清除的数据
alLEntries =true:指定清除这个缓存中所有的数据
@ CacheEvict 与其他不同的是多了 boolean beforeInvocation () default false;翻译就是是否在方法之前执行。
默认代表缓存清除操作是在方法之后执行,如果出现异常缓存就不会清除
beforeInvocation =true:代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除。
如果删掉2号员工,方法出现异常,缓存就不会被清除。
@CacheEv(value="emp",key="#id")
public void deleteEmp(Integer id){
System. out. println("de1eteEmp:"+id)}
// employeeMapper . deleteEmpById (id);
}
测试过程如下:
package com. atguigu. cache. controller ;
import,.
@ RestController
public class EmployeeController {
@Autowired
EmployeeService employee Service;
@ GetMapping ("/emp/{id}")
publicEmployeegetEmployee (@ PathVariable ("id")Integerid){Employee employee= emp1oyeeService .getEmp(id);
return employee;
}
@ GetMapping ("/emp")
public Employee update(Employee employee){
Employee emp= employeeService .updateEmp(employee);
return emp;
)
@ GetMapping ("de1emp")
public String deleteEmp(Integer id){
return"success"
}
}
控制台打印出查询1号员工,说明用了数据库。
查2号员工,控制台没有发语句。
将所以数据删除之后,发现查询1号员工会查数据库,第二次查询不会查数据库。
查询2号员工,控制台还会被打印。