测试代码如下
@GetMapping("/emp")
public Employee updateEmployee(Employee employee){
return employeeService.updateEmp(employee);
}
@EnableCaching
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames={"emp"},keyGenerator = "myKeyGenerator")
public Employee getEmpById(Integer id){
System.out.println("查询 " + id + " 号员工");
return employeeMapper.getEmpById(id);
}
@CachePut(cacheNames = {"emp"})
public Employee updateEmp(Employee employee){
System.out.println("Update Emp : " + employee);
employeeMapper.updateEmp(employee);
return employee;
}
}
先查出1号员工的信息,然后更新,再次查询1号员工,发现1号员工的信息并没有改变!
更新前:
更新时:
更新后:
更新数据库的数据后,缓存内的数据并未更新
原因是getEmpById和updateEmp所使用的key生成规则不同:
前者为自定义的KeyGenerator
后者为默认的new SimpleKey(params)
统一key的生成规则为employee的id:
@EnableCaching
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames={"emp"},key = "#id")
public Employee getEmpById(Integer id){
System.out.println("查询 " + id + " 号员工");
return employeeMapper.getEmpById(id);
}
@CachePut(cacheNames = {"emp"},key = "#result.id")
public Employee updateEmp(Employee employee){
System.out.println("Update Emp : " + employee);
employeeMapper.updateEmp(employee);
return employee;
}
}