Search code examples
javaspringehcachespring-cache

Evict all element in EhCache


I am using EhCache with spring and need to expose an endpoint that will evict all element in given EhCache. But I am not able to find any method that evict all element. It is trivial and might be discussed already but I could not find any resource on internet. Please provide pointers.


Solution

  • are you using Spring Cache ? then set true to allEntries property

    @Cacheable("myCache")
    public String getCache() {
        try {
            Thread.sleep(3000);
        } catch (final InterruptedException e) {
        }
        return "aaa";
    }
    
    @CacheEvict(cacheNames = "myCache", allEntries = true)
    public void evictAll() {
    }
    

    or if you want to delete all caches that you defined

    @Autowired
    CacheManager cacheManager;
    
    public void evictAll() {
        cacheManager.getCacheNames()
                .stream()
                .forEach(n -> cacheManager.getCache(n).clear());
    }