【问题标题】:Transforming existing cache as map to Spring @Cacheable将现有缓存作为映射转换为 Spring @Cacheable
【发布时间】:2018-05-30 14:57:27
【问题描述】:

目前,我有一种使用 Jooq 存储方法在数据库上进行插入的方法。每次存储记录时,都会将其添加到本地缓存中,该缓存基本上是一个地图,其 Id 来自前面(我需要存储以供以后使用)和保存时生成的 Id。所以基本上:

private Map<String, Integer> cache = new HashMap<>();
public insert(List<Customer> customers>{

     //some code to convert Customer to jooq generated CustomerRecord, 
     //which implements UpdatableRecord from Jooq

     record.store();
     cache.put(record.getFrontId(), record.getId());
}
public int find(String frontId) { return cache.get(frontId); }

目前一切正常,但管理这一切需要付出很多努力。如何在 Spring @Cacheable 中使用这样的缓存?我从未使用过它,但我尝试添加 @CacheEvict(value="customer", key="#frontId")给find方法,当然调用的时候缓存是空的。

【问题讨论】:

    标签: java spring-boot caching jooq


    【解决方案1】:

    这是给你的例子……(参数自动是缓存键(你可以在Cacheable中用(key="#search.keyword)指定它):

    @Cacheable(value="customercache")
    public Customer find(String customerkey) {
        return //Load some customer; 
     }
    
    1. 缓存在他实现的缓存中查找是否可以找到客户键,如果有键,则返回客户并且方法体不被调用。
      1. 如果缓存没有找到任何键条目,它会调用正文并返回客户,现在它也存储在缓存中。

    真正重要的是,不要忘记在main方法中激活缓存。

    @SpringBootApplication
    @EnableCaching
    public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    }
    

    【讨论】:

    • 保存整个客户实体不是矫枉过正吗?我只需要它的 ID
    • 比你只返回那里的 id
    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 2013-05-30
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多