使用密钥更新缓存中的新数据

时间:2018-03-28 22:24:52

标签: spring caching spring-cache

我有一个场景,如果用户通过Cache-Control : max-age=0,那么我需要使用底层服务而不是从缓存中获取数据。但我还需要将此记录存储在缓存中,即更新缓存。如果cacheControl为null或其他内容,则从缓存数据中获取。

目前我有

@Cacheable(key = "T(com.org.Utils).idKey(#id)",
  condition = "T(com.org.Utils).isCachingAllowed(#cacheControl)")
  public UserData get(String id, String cacheControl) {
      //Delegating to services and do the actual thing.
  }

所以目前我要将它留给callie做一个cache.put(idKey(id), userData),我觉得这是不正确的。

有没有办法使用注释来做到这一点。我在看@CachePut ,但我认为这对我没有帮助。也不建议同时使用两者。

1 个答案:

答案 0 :(得分:1)

@CachePut完全符合您的要求。摘自javadoc

  

与@Cacheable注释相比,此注释不会导致跳过建议的方法。相反,它总是导致调用方法并将其结果存储在关联的缓存中。

IMO,错误将Cache-Control的逻辑归结为服务。您需要将该逻辑提取一级并调用适当的方法。