如何以编程方式清除spring配置的java项目中的ehcahe对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24955537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:57:15  来源:igfitidea点击:

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

javaspringcachingehcache

提问by BITSSANDESH

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.

这里的cacheManger 是@Autowired EhCacheCacheManager cacheManager 的对象。即使我尝试过 cache.evict(name); 但是当涉及到键控缓存时,所有这些 hack 对我都不起作用。

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.

所以我想刷新我所有的 ehcached 缓存对象。

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);
        }

回答by Przemek Nowak

JavaslangVavr + cache manager:

JavaslangVavr + 缓存管理器:

        List.ofAll(cacheManager.getCacheNames())
            .map(cacheManager::getCache)
            .forEach(Cache::clear);

回答by GreenTurtle

With Spring 4 upwards and Java 8 upwards you can write:

随着 Spring 4 以上和 Java 8 以上,您可以编写:

cacheManager.getCacheNames().stream()
   .map(cacheManager::getCache)
   .forEach(Cache::clear);

This is similar to Przemek Nowaks answer but without the need to use a static Listmethod.

这类似于 Przemek Nowaks 的回答,但不需要使用静态List方法。