目前,我有一种使用 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 方法,但是调用时缓存当然是空的。
最佳答案
这是给您的一个示例...(参数自动为缓存键(您可以在 Cacheable 中使用 (key="#search.keyword) 指定它):
@Cacheable(value="customercache")
public Customer find(String customerkey) {
return //Load some customer;
}
- 缓存会检查他是否可以在他实现的缓存中找到客户 key ,如果有 key ,则返回客户并且不调用方法主体。
- 如果缓存没有找到任何键条目,它会调用正文并返回客户,现在它也存储在缓存中。
真正重要的是,不要忘记在主方法中激活缓存。
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
关于java - 将现有缓存转换为 Spring @Cacheable 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607839/