I want to clear the cache using JAVA code.
and for this goal I write this code:
public void clearCache(){
CacheManager.getInstance().clearAll();
}
is this code correct? and is there a way to confirm that it works good? thanks
I want to clear the cache using JAVA code.
and for this goal I write this code:
public void clearCache(){
CacheManager.getInstance().clearAll();
}
is this code correct? and is there a way to confirm that it works good? thanks
Yes, your code cleares all caches you have in your cacheManager.
The ehcache-documentation says:void clearAll()
Clears the contents of all caches in the CacheManager, but without removing any caches
If you want to test it, you can add some elements to your cache, call clearCache()
and then try to get the values. The get()
-method should only return null
.
You can't add values directly in your cacheManager, it just manages the caches you declared in your configuration file. (by default it's ehcache.xml, you can get that on the ehcache homepage.) You also can add caches programmatically, even without knowing anything about the configuration.
CacheManager cacheManager = CacheManager.getInstance();
Ehcache cache = new Cache(cacheManager.getConfiguration().getDefaultCacheConfiguration());
cache.setName("cacheName");
cacheManager.addCache(cache);
To add a value to the cache you have to make an Element:
Element element = new Element(key, value)
and simply call cache.put(element)
.
If your cache-variable isn't visible anymore, but your cacheManager is, you can do the same with cacheManager.getCache(cacheName).put(element)
I hope this helps...
If you know the cache name, you can retrieve it from the CacheManager and use removeAll().
CacheManager manager = CacheManager.getInstance();
Ehcache cache = manager.getCache(cacheName);
cache.removeAll();
Your approach works, but it will clear all caches' objects.
There are 2 ways to achieve this:
Answer above mentioned net.sf.ehcache.CacheManager
of Ehcache.
In common case org.springframework.cache.CacheManager
is Spring interface.
For clearing all you need to inject it and clear all named caches:
@Autowired
CacheManager cacheManager;
public void clearAllCaches() {
cacheManager.getCacheNames().forEach(name -> cacheManager.getCache(name).clear());
}
© 2022 - 2024 — McMap. All rights reserved.