简体   繁体   中英

ehcache 3 cache-through with spring boot and JPA

  • spring boot version: 1.4.1.RELEASE
  • ehcache version: 3.1.3
  • OS: mac 10.11.6
  • java: 1.8.0_91

I followed along w/ "Caching 101" with Louis Jacomet & Aurelien Broszniowski to get my feet wet with cache-through using ehcache 3.

There are a few things this presentation glazes over (but mentions briefly). One of them is cache key management, which now becomes the application's responsibility; since the objects/data created are cached 1st b/f they are persisted (the whole point of cache-through) we don't have available to us the db-generated 'id' which is returned (JPA) ... we have to add a new field to the Entity to store this cache key.

So, I created a 'key generator' that maintains a Set of Long, cache keys. Fine. But, when the application stops, this Set goes away. So, if there were any objects/entries created while the application was running & persisted in the db, on startup, these records need to be inserted into the application cache AND the cache key (Set) needs to be populated as well.

In my sample code , my rest controller is the one who interacts w/ the cache and I added a method to accomplish this. It calls repository.findAll() to populate a List of entities (Product in this case). Since each, previously-persisted entity also persisted the cache key, I iterate through this list & populate the cache; or so I think.

    @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()");
}

But, when, after the console confirms that the app. has started, I navigate to a rest endpoint to get said list, its empty!

So, my question is, how to populate the cache on startup with any persisted data.

Use BootstrapCacheLoader
See http://www.ehcache.org/documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM