I have a requirement to use old/stale cache value if cache refresh is failed. I have gone through the many examples on internet and decided to try with caffeine cache to implement this requirements(more specifically using refreshAfterWrite feature). I am able to cache the data using caffeine but not able to get old/stale value when cache refresh(rest api is failed) is failed. I have used SimpleCacheManager(org.springframework.cache.support.SimpleCacheManager) and CaffeineCache.
**simpleCacheManager bean code** :
<bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches" ref="caffeineCaches" />
</bean>
**caffeine cache** :
@Bean
public Collection<? extends org.springframework.cache.Cache> caffeineCaches(){
Collection<CaffeineCache> caffeineCaches = new ArrayList<>();
caffeineCaches.add(new CaffeineCache("pbdBankRegistry",
Caffeine.newBuilder()
.refreshAfterWrite(2, TimeUnit.MINUTES)
.initialCapacity(1)
.maximumSize(2)
.recordStats()
.build(new CustomCacheLoader()),false));
return caffeineCaches;
}
**CacheLoader Code :**
public class CustomCacheLoader implements CacheLoader<Object, Object> {
@Nullable
@Override
public Object load(Object o) throws Exception {
return null;
}
@Override
public Map loadAll(Set keys) throws Exception {
return CacheLoader.super.loadAll(keys);
}
@Override
public CompletableFuture asyncLoad(Object key, Executor executor) throws Exception {
return CacheLoader.super.asyncLoad(key, executor);
}
@Override
public CompletableFuture<? extends Map> asyncLoadAll(Set keys, Executor executor) throws Exception {
return CacheLoader.super.asyncLoadAll(keys, executor);
}
@Nullable
@Override
public Object reload(Object key, Object oldValue) throws Exception {
return CacheLoader.super.reload(key, oldValue);
}
@Override
public CompletableFuture asyncReload(Object key, Object oldValue, Executor executor) throws Exception {
return CacheLoader.super.asyncReload(key, oldValue, executor);
}
I think i have to call my api from reload method or from build method of Caffeine. but i am not sure. I am new with the cache so here need your help to implement this code.
Note : My application is on spring 4.3.3.RELEASE version.