【问题标题】:ehcache 3 cache-through with spring boot and JPA带有spring boot和JPA的ehcache 3缓存
【发布时间】:2017-02-22 23:42:12
【问题描述】:
  • spring boot 版本:1.4.1.RELEASE
  • ehcache 版本:3.1.3
  • 操作系统:mac 10.11.6
  • java: 1.8.0_91

我跟随 "Caching 101" with Louis Jacomet & Aurelien Broszniowski 使用 ehcache 3 进行缓存直通。

此演示文稿有一些内容令人印象深刻(但简要提及)。其中之一是缓存密钥管理,现在成为应用程序的责任;因为创建的对象/数据在第一次 b/f 中被缓存,所以它们被持久化(整个缓存通过点),我们无法获得返回的 db 生成的“id”(JPA)......我们有向实体添加一个新字段以存储此缓存键。

因此,我创建了一个“密钥生成器”,用于维护一组长缓存密钥。美好的。但是,当应用程序停止时,这个 Set 就消失了。因此,如果在应用程序运行时创建了任何对象/条目并保存在数据库中,则在启动时,需要将这些记录插入到应用程序缓存中,并且还需要填充缓存键 (Set)。

In my sample code,我的休息控制器是与缓存交互的人,我添加了一种方法来实现这一点。它调用 repository.findAll() 来填充实体列表(在本例中为 Product)。由于每个先前保留的实体也保留了缓存键,因此我遍历此列表并填充缓存;或者我认为。

    @PostConstruct
        private void initializeCacheFromDB() {
    List<Product> productList = new ArrayList<>();
    repository.findAll().forEach(productList::add);

    for (Product product : productList) {
        // update the cache
        // NOTE: below has no effect!
        productCache.put(product.getCacheKey(), product);
        // update/set the keys
        CustomKeyGenerator.addKey(product.getCacheKey());
    }

    // does nothing!!!! ... no entries so keys not associated w/ Product(s)
    //productCache.getAll(CustomKeyGenerator.getKeysSet());

    System.out.println("done w/ initializeCacheFromDB()");
}

但是,当控制台确认该应用程序之后。已经开始,我导航到一个休息端点来获取所说的列表,它是空的!

所以,我的问题是,如何在启动时使用任何持久数据填充缓存。

【问题讨论】:

    标签: java spring-boot spring-data-jpa ehcache


    【解决方案1】:

    使用 BootstrapCacheLoader
    http://www.ehcache.org/documentation

    【讨论】: