java - 将现有缓存转换为 Spring @Cacheable 的映射

标签 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 方法,但是调用时缓存当然是空的。

最佳答案

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

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

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

@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/

相关文章:

java - 将外部 jar (lib/*.jar) 添加到 IntelliJ IDEA 项目的正确方法

c# - Java 和 C# 中的多维数组

java - 关于Jms发布订阅者模型的建议

java - SQL语句MyBatis中未知元素<select>

java - @PathVariable fileName 结果为 406 Not Acceptable

java - Liquibase 是否在 Spring Boot 应用程序中注册所有 bean 之前运行?

javascript - AngularJS 摘要回调

java - 用于投影的 Hibernate 缓存

caching - Cloudfront私有(private)内容+签名url架构

java - 设置颜色项目 ListView xml