将现有缓存转换为映射到Spring @Cacheable

时间:2018-05-30 14:57:27

标签: java spring-boot caching jooq

目前,我有一个使用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方法,但当调用它时缓存是空的。

1 个答案:

答案 0 :(得分:1)

这是一个例子...(参数自动为缓存键(您可以在Cacheable中使用(key =“#search.keyword)指定它):

@Cacheable(value="customercache")
public Customer find(String customerkey) {
    return //Load some customer; 
 }
  1. 缓存查看是否可以在其实现的缓存中找到customerkey,如果它具有密钥,则返回客户并且方法体不会被调用。
    1. 如果缓存没有找到任何密钥条目,它会调用正文并返回客户,现在它也存储在缓存中。
  2. 真正导入的是,不要忘记在main方法中激活缓存。

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