Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear ehcahe objects in spring configured java project programmatically

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);
        }
like image 442
BITSSANDESH Avatar asked Feb 12 '23 09:02

BITSSANDESH


1 Answers

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.

like image 82
GreenTurtle Avatar answered Feb 15 '23 09:02

GreenTurtle