如何以编程方式清除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
How can I clear ehcahe objects in spring configured java project programmatically
提问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 Andres
Use the Cache.clear()
method.
使用Cache.clear()
方法。
Take a look at this: http://docs.spring.io/spring/docs/3.2.9.RELEASE/javadoc-api/org/springframework/cache/Cache.html#clear()
看看这个:http: //docs.spring.io/spring/docs/3.2.9.RELEASE/javadoc-api/org/springframework/cache/Cache.html#clear()
回答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 List
method.
这类似于 Przemek Nowaks 的回答,但不需要使用静态List
方法。