Clearing cache with cacheManager in java

I want to clear the cache using JAVA code.

and for this purpose I am writing this code:

public void clearCache(){ CacheManager.getInstance().clearAll(); } 

Is this code correct? and is there any way to confirm that it works well? thanks

+4
source share
3 answers

Yes, your code clears all the caches that 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 return only null .

You cannot add values ​​directly to cacheManager, it just manages the caches specified in the configuration file. (The default is ehcache.xml, you can get it on the ehcache homepage.) You can also add the cache programmatically, without even 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 must create an element: Element element = new Element(key, value) and just call cache.put(element) . If your cache variable is no longer visible, but your cacheManager is, you can do the same with cacheManager.getCache(cacheName).put(element)

Hope this helps ...

+5
source

If you know the name of the cache, you can get it from CacheManager and use removeAll () .

 CacheManager manager = CacheManager.getInstance(); cache = manager.getCache(cacheName); cache.removeAll(); 

Your approach works, but it will clear all cache objects.

+4
source

There are two ways to achieve this:

  • Using dev-console: if you are using the corporate version of ehcache that comes with the Terracotta Server Array (TSA), you can find dev-console.bat or dev-console.sh based in the installed directory In this case, you can use this file and connect to the TSA server (if the default settings are used to connect to the local host: 9520), select the named cache manager, and then on the "Browse" tab, select the "Clear Caches" button and select the required caches to clear in the listing. This will clear the cache contents of the selected caches and can be checked on the calibration tab where the displayed memory chart is displayed.
  • Using open source eHCache: using the api cache manager, flushing the cache as described in the question, and then checking, using cache receipt for a specific key, is null.
0
source

Source: https://habr.com/ru/post/1501254/


All Articles