Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing cache using cacheManager in java

Tags:

java

ehcache

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

like image 298
mimo Avatar asked Sep 09 '13 07:09

mimo


People also ask

How do I clear my ehcache cache?

To empty the entire cache, use Cache. removeAll() . If the cache itself is removed ( Cache. dispose() or CacheManager.

How do I clear the cache in eclipse?

Open Eclipse and navigate to the Window > Preferences. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. 3. Click the Clear Cached Files button in the File Cache window.

How do I clear my spring boot cache?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.


2 Answers

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...

like image 60
Kayz Avatar answered Oct 16 '22 15:10

Kayz


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.

like image 32
Gaʀʀʏ Avatar answered Oct 16 '22 17:10

Gaʀʀʏ