How to temporarily disable caching for Spring cache
Inspired by SimY4 last comment, here is my working solution overloading SimpleCacheManager
in order to provide runtime switch.
Just use switchableSimpleCacheManager.setEnabeld(false/true)
to switch off/on.
package ch.hcuge.dpi.lab.cache;
import org.springframework.cache.Cache;
import org.springframework.cache.support.NoOpCache;
import org.springframework.cache.support.SimpleCacheManager;
/**
* Extends {@link SimpleCacheManager} to allow to disable caching at runtime
*/
public class SwitchableSimpleCacheManager extends SimpleCacheManager {
private boolean enabled = true;
public boolean isEnabled() {
return enabled;
}
/**
* If the enabled value changes, all caches are cleared
*
* @param enabled true or false
*/
public void setEnabled(boolean enabled) {
if (enabled != this.enabled) {
clearCaches();
}
this.enabled = enabled;
}
@Override
public Cache getCache(String name) {
if (enabled) {
return super.getCache(name);
} else {
return new NoOpCache(name);
}
}
protected void clearCaches() {
this.loadCaches().forEach(cache -> cache.clear());
}
}
Configuration ( using Caffeine ):
@Bean
public SwitchableSimpleCacheManager cacheManager() {
SwitchableSimpleCacheManager cacheManager = new SwitchableSimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
buildCache(RESULT_CACHE, 24, 5000)
));
return cacheManager;
}
private CaffeineCache buildCache(String name, int hoursToExpire, long maxSize) {
return new CaffeineCache(
name,
Caffeine.newBuilder()
.expireAfterWrite(hoursToExpire, TimeUnit.HOURS)
.maximumSize(maxSize)
.build()
);
}
What I was looking for was NoOpCacheManager:
To make it work I switched from xml bean creation to a factory
I did something as follows:
@Bean
public CacheManager cacheManager() {
final CacheManager cacheManager;
if (this.methodCacheManager != null) {
final EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
ehCacheCacheManager.setCacheManager(this.methodCacheManager);
cacheManager = ehCacheCacheManager;
} else {
cacheManager = new NoOpCacheManager();
}
return cacheManager;
}