带有列表的 Spring @Cacheable 方法

标签 spring ehcache jdbctemplate

我在 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。

最佳答案

不要认为那是可能的。 List<Integer>将是对 getContactList 的返回值的键将保存在缓存中。

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

一种选择是改变你的方法 getContactList(List<Integer> contactIdList)getContact(Integer id) - 在这种情况下,构建缓存可能需要一段时间,但是一旦给定 ID 的联系人在缓存中,DB 将不会在以后的调用中用于重新获取它。

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

关于带有列表的 Spring @Cacheable 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31220740/

相关文章:

java - 插入新记录时 hibernate 缓存查询未更新

sql - 使用 Spring DAO 的 NamedParameterJDBCTemplate,如何为多列 IN 语句编码?

java - MVC 架构 DTO/模型映射/转换

java - URL 和方法的 spring 安全设置

java - SpringJUnit4ClassRunner 测试——从 ant 工作,而不是从 IDE

java - org.hibernate.service.UnknownServiceException : Unknown service requested

java - Ehcache与数据库不同步

跨 AWS 集群的 Spring、Tomcat 8 Ehcache 复制(在 EC2 实例上)

java - 使用Spring JdbcTemplate提取一个字符串

java - 使用jdbcTemplate在Spring mvc中从mysql数据库读取blob类型图像