I am trying to write an application to cache which reloads every few seconds. I decided to use spring boot Caffeine and got a sample application too. But when I am specifying refreshAfterWrite property, it throws exception: refreshAfterWrite requires a LoadingCache
spring:
cache:
cache-names: instruments, directory
caffeine:
spec: maximumSize=500, expireAfterAccess=30s, refreshAfterWrite=30s
To resolve this I provide Loading Cache Bean, but cache stopped working altogether:
@Bean
public CacheLoader<Object, Object> cacheLoader() {
return string -> {
System.out.println("string = " + string);
return string;
};
}
@Bean
public LoadingCache<Object, Object> loader(CacheLoader<Object, Object> cacheLoader) {
return Caffeine.newBuilder()
.refreshAfterWrite(1, TimeUnit.SECONDS)
.build(cacheLoader);
}
Do we have some simple way for reload to work?
To conclude here, using the LoadingCache
feature of Caffeine with Spring's cache abstraction does not make much sense since they share a lot of features.
@Cacheable
typically provide a way to mark a method to retrieve an element that is not present in the cache yet. LoadingCache
achieves the same scenario, requiring you to provide a handle that can load a missing element by id.
If you absolutely need to use a LoadingCache
, I'd inject the Cache
in your code and interact with it programmatically.