On app start, I initialized ~20 different caches:
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(many many names));
return cacheManager;
}
I want to reset all the cache at an interval, say every hr. Using a scheduled task:
@Component
public class ClearCacheTask {
private static final Logger logger = LoggerFactory.getLogger(ClearCacheTask.class);
private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
@Value("${clear.all.cache.flag}")
private String clearAllCache;
private CacheManager cacheManager;
@CacheEvict(allEntries = true, value="...............")
@Scheduled(fixedRate = 3600000, initialDelay = 3600000) // reset cache every hr, with delay of 1hr
public void reportCurrentTime() {
if (Boolean.valueOf(clearAllCache)) {
logger.info("Clearing all cache, time: " + formatter.print(DateTime.now()));
}
}
}
Unless I'm reading the docs wrong, but @CacheEvict
requires me to actually supply the name of the cache which can get messy.
How can I use @CacheEvict
to clear ALL caches?
I was thinking instead of using @CacheEvict
, I just loop through all the caches:
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
I just used a scheduled task to clear all cache using the cache manager.
Gets the job done.
Below evictCache method evicts fooCache using @CacheEvict annotation.