【问题标题】:Spring @Cacheable methods with lists带有列表的 Spring @Cacheable 方法
【发布时间】:2015-09-22 02:49:42
【问题描述】:

我在 Spring 4.1.4 应用程序中使用了最新的 Ehcache。我有的是:

class Contact{
    int id;
    int revision;
}    

@Cacheable("contacts")
public List<Contact> getContactList(List<Integer> contactIdList) {
    return namedJdbc.queryForList("select * from contact where id in (:idlist)", Collections.singletonMap("idlist", contactIdList));
}

@CachePut(value="contact", key = "id")
public void updateContact(Contact toUpdate) {
    jdbctemplate.update("update contact set revision = ? where id = ?", contact.getRevision(), contact.getId());
}

我想要实现的是,联系人存储在缓存中,当我再次调用getContactList 方法时,所有id 已缓存的联系人都将从缓存中检索,其他联系人应该正常查询然后缓存。然后,此缓存应在更新时更新缓存的联系人实体。

我使用的是纯 Spring JDBC 和 Ehcache,没有 JPA 也没有 Hibernate。

【问题讨论】:

    标签: spring ehcache jdbctemplate


    【解决方案1】:

    不要认为这是可能的。 List&lt;Integer&gt; 将是 key,而 getContactList 的返回值将保存在缓存中。

    因此,除非输入到您的getContactList 的 ID 列表包含与先前调用之一完全相同的 ID,否则它将是缓存未命中,并且将从 DB 中获取数据。 (注意:如果两个列表完全包含相同的元素且顺序相同,则认为它们相等)

    一种选择是将您的方法 getContactList(List&lt;Integer&gt; contactIdList) 更改为 getContact(Integer id) - 在这种情况下,构建缓存可能需要一段时间,但是一旦给定 ID 的联系人在缓存中,数据库将不会用于重新在以后的调用中获取它。

    虽然不优雅,但另一种选择是在 getContactList 方法中手动进行缓存。

    【讨论】:

      【解决方案2】:

      为我工作。这是我的答案的链接。 https://stackoverflow.com/a/60992530/2891027

      TL:DR

      @Cacheable(cacheNames = "test", key = "#p0")
      public List<String> getTestFunction(List<String> someIds) {
      

      答案中有关我的环境的更多信息。

      【讨论】:

        猜你喜欢
        • 2015-05-27
        • 2019-05-08
        • 2018-05-06
        • 1970-01-01
        • 2018-11-30
        • 2018-11-05
        • 2012-05-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多