【问题标题】:Search for cached data only when a particular method invokes仅在特定方法调用时才搜索缓存数据
【发布时间】:2017-10-08 01:46:08
【问题描述】:

我想知道是否只有在从特定方法调用时才能获取缓存数据,例如我有一个注释为@Cacheable 的方法,我希望它只返回特定方法调用它时缓存的内容,否则,正常执行该方法。

【问题讨论】:

    标签: java spring caching spring-boot ehcache


    【解决方案1】:

    使用 Spring 缓存抽象。 https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html

    @Cacheable({"users"})
    public User getUser(String userId) {
    // Logic goes here
    }
    

    有了这个,任何 Spring 都会缓存从方法返回的返回对象,方法输入作为键。所以这个方法被调用,如果找到,则从缓存中返回用户,否则调用实际方法,缓存并返回响应。

    这可以由任何第三方缓存支持,例如 redis、ehcache、hazelcast。

    【讨论】:

    • 对不起,您能否解释一下这个答案是如何提出的问题。当从任何方法(使用相同的参数)调用时,您指示的代码 sn-p 将返回缓存的对象。但问题是不同的。当从特定方法调用缓存方法(使用@Cacheable)时,才需要返回缓存条目,否则它应该遵循方法内部的常规代码流。对不起,如果我在这里遗漏了什么。
    【解决方案2】:

    是的,您可以使用@Cacheable Annotation 的条件参数来做到这一点。在这里查看http://docs.spring.io/spring/docs/3.1.0.RC1/spring-framework-reference/html/cache.html 第 28.3.1.3 节

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      相关资源
      最近更新 更多