I'm using spring-cache to improve database queries, which works fine as follows:
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("books");
}
@Cacheable("books")
public Book getByIsbn(String isbn) {
return dao.findByIsbn(isbn);
}
But now I want to prepopulate the full book-cache on startup. Which means I want to call dao.findAll()
and put all values into the cache. This routine shall than only be scheduled periodically.
But how can I explicit populate a cache when using @Cacheable
?
I have encountered the following problem when using @PostConstruct: - even though the method I wanted to be cached was called, after calling it from swagger, it still didn't use the cached value. Only after called it once more.
That was because @PostConstruct is too early for caching something. (At least I think that was the issue)
Now I'm using it more late in the startup process and it works without problems:
An option would be to use the
CommandLineRunner
for populating the cache on startup.From official CommandLineRunner documentation, it is an:
Hence, we just need to retrieve the list of all available books and then, using
CacheManager
, we populate the book cache.As Olivier has specified, since spring caches output of function as a single object, using @cacheable notation with findAll will not allow you to load all objects in cache such that they can later be accessed individually.
One possible way you can load all objects in cache is if caching solution being used provides you a way to load all objects at startup. E.g solutions like NCache / TayzGrid provides Cache startup loader feature, that allows you to load cache at startup with objects using a configurable cache startup loader.
Add another bean BookCacheInitialzer
Autowire the current bean BookService in BookCacheInitialzer
in PostConstruct method of BookCacheInitialzer pseudo code
Then can do something like
}
}
If having all instances of Book in memory at startup is your requirement than you should store them in some buffer yourself. Putting them in the cache with the findAll() method means that you must annotate findAll() with @Cacheable. Then you would have to call findAll() at startup. But that does not mean that calling getByIsbn(String isbn) will access the cache even if the corresponding instance has been put in the cache when calling findAll(). Actually it won't because ehcache will cache method return value as a key/value pair where key is computed when method is called. Therefore I don't see how you could match the return value of findAll() and return value of getByIsbn(String) because returned types are not the same and moreover key won't never match for all your instances.
Just use the cache as before, add a scheduler to update cache, code snippet is below.
Make sure your
KeyGenerator
will return the object for one parameter (as default). Or else, expose theputToCache
method inBookService
to avoid using cacheManager directly.