有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java缓存在Spring引导中未得到更新

我使用SpringBoot@CachePut和@Cacheable注释来缓存数据

@CachePut(value = "cache1", key = "#clientId")
public Map<String, Object> buildCache(Long clientId){
Map<String, Object> cacheMap= new HashMap<String, Object>();
//get values from remote db and store them in the local db as well as cache
return cacheMap;
}

@Cacheable(value = "cache1", key = "#clientId")
public Map<String, Object> getFromCache(Long clientId){
     //get from local db
}

在buildCache中,我从远程数据库获取值,并将这些值保存在本地数据库和缓存中。在getCache方法中,我从本地数据库获取值。当我第一次调用getCache方法时,它被执行,本地DB值被保存在缓存中。然后我调用buildCache方法来更新缓存和本地DB值。之后,我再次调用getCache方法来获取更新后的值。但是这个方法仍然返回旧值而不是新值

简而言之,为了刷新缓存,我执行@CachePut方法。但是当我调用@Cacheable方法时,我没有得到更新的值

请告诉我哪里出了问题


共 (1) 个答案

  1. # 1 楼答案

    @CacheEvict(value ="user" ,allEntries = true)
    @CachePut(value = "user",key = "#userDTO.id")
    @PostMapping("user/update")
    public List<User> updateUser(@RequestBody UserDTO userDTO){
        return userService.updateUser(userDTO);
    }
    

    首先删除现有缓存,然后进行更新,以便下次第一次从数据库中获取数据,然后将其存储在缓存中并从缓存中获取数据