【问题标题】:Does @Cacheable annotated methods execute when the actual data is modified?@Cacheable 注解的方法是否在实际数据被修改时执行?
【发布时间】:2019-03-14 14:12:24
【问题描述】:

我正在构建一个可供浏览器或其他 Web 服务使用的 RESTful Web 服务。 我愿意通过缓存来减少带宽,但是我希望执行该方法并仅在它与上次修改的缓存不同时才发送实际数据。

根据我对@cacheable注解的理解,该方法只执行一次,输出被缓存,直到缓存过期。

@CachePut 每次都会执行并更新缓存,但即使没有更新它也会再次发送缓存吗?

总结是:我需要客户端能够发送它的缓存的最后修改日期,并且只有在它被修改后才能获得新数据。

此外,Spring 如何处理客户端缓存和 if-modified-since 标头?我需要保存上次修改时间还是自动处理?

【问题讨论】:

  • 使用观察者模式。如果值已更新,请将缓存中的值替换为新值。并且总是返回缓存中的那个

标签: java rest spring-mvc


【解决方案1】:

不,你需要自己做。

您需要使用@Cacheable(docs) 注释您的“获取”方法,然后使用@CacheEvict (docs) 注释“更新”方法以“删除”您的缓存。因此,当您在修改后下次获取数据时,它会是新鲜的。

或者,您可以使用@CacheEvict 创建另一个方法并从“更新”方法手动调用它。

【讨论】:

    【解决方案2】:

    与缓存相关的注解(@Cacheable@CacheEvict 等)只会处理由应用程序维护的缓存。任何像 last-modified 这样的 http 响应头都必须单独管理。 Spring MVC 提供了一种方便的方法来处理它(docs)。 计算上次修改时间的逻辑显然必须是特定于应用程序的。

    它的用法示例是

    MyController {
    
        @Autowire
         CacheService cacheService;
    
            @RequestMapping(value = "/testCache", method = RequestMethod.GET)
             public String myControllerMethod(WebRequest webRequest, Model model, HttpServletResponse response) {
                long lastModified = // calculate as per your logic and add headers to response
                if (request.checkNotModified(lastModified)) {
                  // stop processing
    
                  return null;
                } else {  
    
                  return cacheService.getData(model);
                }
            }
    
    
        @Component
        public class CacheService{
    
            @Cacheable(value = "users", key = "#id")
            public String getData(Model model) {
                //populate Model
                return "dataview";
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2012-05-07
      • 1970-01-01
      相关资源
      最近更新 更多