【问题标题】:Spring cacheable annotation with multiple key具有多个键的 Spring 可缓存注释
【发布时间】:2018-09-17 19:11:56
【问题描述】:

我有 2 种方法来查找客户记录(代码如下),customerGuid 和 customerId 是 Customer 对象中的 2 个不同字段。

假设我通过 customerId 查找客户一次,有没有办法让我直接从缓存中通过 guid 查找客户而不查询后端,假设这两种方法的返回类型都是客户。

public class CustomerLookup {
    @Cacheable("customerCache")
    public Customer getCustomerByGuid(final String customerGuid) {
        // some implementation here...
    }

    @Cacheable("customerCache")
    public Customer getCustomerByCustId(final String customerId) {
        // some implementation here...
    }
}

【问题讨论】:

    标签: spring spring-cache


    【解决方案1】:

    您可以将第二个参数添加到仅用作缓存键的一种方法。示例使用customerId 作为键并按如下方式进行:

    @Service
    public class CustomerLookup {
       @Autowired
       @Lazy
       private CustomerLookup self;
    
       @CachePut("customerCache", key="#customerId")
       public Customer getCustomerByGuid(final String customerGuid, String customerId) {
         Customer customer = self.getCustomerByCustId(final String customerId);
         //......
       }
    }
    

    注意CustomerLookup 的自注入,如果你不这样做,当你在getCustomerByGuid 中调用getCustomerByCustId(final String customerId) 方法时缓存将不起作用。还要注意getCustomerByGuid 上的@CachePut 而不是@Cacheable,这样您就可以确定每次都会调用此方法。

    【讨论】:

    • 感谢您的回答,但在我的情况下,getCustomerByGuid() 的调用者可能并不总是知道或拥有 customerId。这就是为什么有 2 种查找方法的原因之一。
    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 2019-07-01
    • 2016-09-10
    • 2017-03-14
    • 1970-01-01
    • 2012-09-02
    • 2011-04-12
    • 2014-02-22
    相关资源
    最近更新 更多