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());
Cache eviction is a feature where file data blocks in the cache are released when fileset usage exceeds the fileset soft quota, and space is created for new files. The process of releasing blocks is called eviction. However, file data is not evicted if the file data is dirty.
Method SummaryClear the cache through removing all mappings. Evict the mapping for this key from this cache if it is present. Evict the mapping for this key from this cache if it is present, expecting the key to be immediately invisible for subsequent lookups.
I just used a scheduled task to clear all cache using the cache manager.
@Component
public class ClearCacheTask {
@Autowired
private CacheManager cacheManager;
@Scheduled(fixedRateString = "${clear.all.cache.fixed.rate}", initialDelayString = "${clear.all.cache.init.delay}") // reset cache every hr, with delay of 1hr after app start
public void reportCurrentTime() {
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
}
}
Gets the job done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With