@CachePut后 findAll() 没有从缓存中给出结果



我正在学习spring-boot缓存,以便在我们组织的项目中应用这一概念,我制作了一个名为employe-cache的示例项目。我的控制器和服务组件中有四个方法insert、update、get和getAll。对于插入和获取,@Cacheable工作得很好。现在我第一次调用getAllEmployee(),然后它从数据库中获取数据。之后,我尝试使用@CachePut进行更新,它会更新数据库中的值,我再次调用getAllEmployee(),但它没有从缓存中返回更新后的值。我还参考了@CachePut的文档。我也参考了一些其他类似的文件,但我没有解决我的问题。此外,当我打电话时,不会出现任何错误
我尝试的是
这是我从EmplyeeController.java获得的两个API

@PostMapping(value = "/updateSalary")
private Boolean updateSalary(@RequestParam int salary, @RequestParam Integer id) {
return empService.updateSalary(salary, id);
}
@GetMapping(value = "/getAllEmployee")
private Object getAllEmployee() {
List<EmployeeMapping> empList = empService.getAllEmployee();
return !empList.isEmpty() ? empList : "Something went wrong";
}

这是我在EmployeeService.java中的两种方法。我应用了不同的键来更新方法,但没有成功。我的getAll()方法没有参数,所以我从这里尝试了所有无参数方法的关键技术,但也没有得到任何结果。

@CachePut(key = "#root.method.name")
public Boolean updateSalary(int salary, int id) {
System.err.println("updateSalary method is calling in service");
if (empRepo.salary(salary, id) != 0) {
return true;
}
return false;
}
@Cacheable(key = "#root.method.name")
public List<EmployeeMapping> getAllEmployee() {
return empRepo.findAllEmployee();
}

这是我在EmployeeRepository.java中的两种方法。我在EmployeeMetaModel.javaEmployeeMapping.java中使用了@SqlResultSetMappings@NamedNativeQueries,但在EmployeeMetaModel.java中的本机查询中没有错误,因为它是从数据库中给出结果的。

@Transactional
@Modifying
@Query("update employee_cache e set e.salary = ?1 where e.id = ?2")
int salary(int salary, int id);
@Query(name = "EmployeeListQuery", nativeQuery = true)
List<EmployeeMapping> findAllEmployee();

请帮助我解决这个问题,我只需要在调用updateSalary()后使用getAllEmployee()从缓存中更新一个值。

如何通过注释定义缓存存在问题。您的@CachePut@Cacheable不使用相同的缓存密钥。你实际上应该拥有这样的东西:

@CachePut(value = "employees", key = "T(org.springframework.cache.interceptor.SimpleKey).EMPTY")
public List<EmployeeMapping> updateSalary(int salary, int id) {
// update salary and return the list of employees
}
@Cacheable(value = "employees")
public List<EmployeeMapping> getAllEmployee() {
// return the list of employees
}

这里@CachePut@Cacheable具有相同的缓存关键字。d现在,当您调用updateSalary()方法时,@CachePut将用该方法的结果,即具有更新工资的员工列表,替换关键字"employees">的现有缓存值。

最新更新