Reputation: 1135
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);
}
Upvotes: 4
Views: 13628
Reputation: 7693
Javaslang Vavr + cache manager:
List.ofAll(cacheManager.getCacheNames())
.map(cacheManager::getCache)
.forEach(Cache::clear);
Upvotes: 3
Reputation: 1262
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.
Upvotes: 4
Reputation: 10717
Use the Cache.clear()
method.
Take a look at this: http://docs.spring.io/spring/docs/3.2.9.RELEASE/javadoc-api/org/springframework/cache/Cache.html#clear()
Upvotes: 2