Is it possible to schedule spring cache eviction to everyday at midnight?
I've read Springs Cache Docs and found nothing about scheduled cache eviction.
I need to evict cache daily and recache it in case there were some changes outside my application.
Try to use @Scheduled Example:
@Scheduled(fixedRate = ONE_DAY)
@CacheEvict(value = { CACHE_NAME })
public void clearCache() {
log.debug("Cache '{}' cleared.", CACHE);
}
You can also use cron expression with @Scheduled.
If you use @Cacheable on methods with parameters, you should NEVER forget the allEntries=true annotation property on the @CacheEvict, otherwise your call will only evict the key parameter you give to the clearCache() method, which is nothing => you will not evict anything from the cache.
Maybe not the most elegant solution, but @CacheEvict was not working, so I directly went for the CacheManager.
This code clears a cache called foo via scheduler:
class MyClass {
@Autowired CacheManager cacheManager;
@Cacheable(value = "foo")
public Int expensiveCalculation(String bar) {
...
}
@Scheduled(fixedRate = 60 * 1000);
public void clearCache() {
cacheManager.getCache("foo").clear();
}
}