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

问题描述 投票:0回答:1

我正在学习Spring Boot缓存,以将这一概念应用到我们组织的项目中,并且我创建了一个示例项目,称为员工缓存。我的控制器和服务组件中有四个方法insert,update,get和getAll。对于insert和get @Cacheable来说,它工作正常。现在,我第一次调用getAllEmployee(),然后它正在从数据库中获取数据。之后,我尝试使用@CachePut更新它更新数据库中的值,然后再次调用getAllEmployee(),然后它没有从缓存中返回更新的值。我也将documentation称为@CachePut。我还参考了其他一些文档,例如thisthis,但我没有解决问题。另外,当我打电话时,不会出现任何错误。我试过的是这是我来自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()方法没有参数,因此我尝试了here中没有参数方法的所有键技术,然后我也没有得到任何结果。

@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的两种方法。我在@SqlResultSetMappings中将@NamedNativeQueriesEmployeeMetaModel.javaEmployeeMapping.java一起使用,但在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();

请帮助我摆脱这个,我只需要在调用getAllEmployee()之后使用updateSalary()从缓存中获取更新的值。

java spring-boot spring-cache
1个回答
0
投票

如何通过注释定义缓存存在问题。您的@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”替换现有的缓存值,并返回结果的方法,即更新工资的员工列表。

© www.soinside.com 2019 - 2024. All rights reserved.