Now my project need is to trigger the flushing of all active cached objects. Based on all my findings I have written the following code.
Collection<String> names = cacheManager.getCacheNames();
for (String name : names) {
Cache cache = cacheManager.getCache(name);
cache.put(name, null);
}
Here cacheManger is the object of @Autowired EhCacheCacheManager cacheManager. Even i have tried cache.evict(name); But all these hack doesn't work for me, when it comes for keyed caches.
Yes too i have tried the annotation based envition using following code snippets:
@Caching(evict = { @CacheEvict(value = "cache1", allEntries = true), @CacheEvict(value = "cache2", allEntries = true) })
public static boolean refresh() {
return true;
}
So the whole point I want to flush all my ehcached cached object.
I got one understanding towards the clearing all the cached, if i could get all the keys then I could flush them by using following code snippet:
Cache cache = cacheManager.getCache(nameOfCache);
if (cache.get(keyOfCache) != null) {
cache.put(keyOfCache, null);
}
With Spring 4 upwards and Java 8 upwards you can write:
cacheManager.getCacheNames().stream()
.map(cacheManager::getCache)
.forEach(Cache::clear);
This is similar to Przemek Nowaks answer but without the need to use a static List
method.
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