Reputation: 153
I am calling fetchCatchAndClear method where I am passing List and it consists of cache names. Can someone help me how to iterate over the list and clear the cache based on the Cache Name coming from List of String. Also if the list is empty I should clear all the caches present.
Upvotes: 0
Views: 3101
Reputation: 2542
A rather simple approach which sticks to the org.springframework.cache.CacheManager
could be the following:
List<String> cacheNames = List.of("aCache", "anotherCache"); // the list you are passing in
CacheManager cacheManager = new SimpleCacheManager(); // any cache manager you are injecting from anywhere
// a simple iteration, exception handling omitted for readability reasons
cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
Evicting all caches is also that simple, except that you have to query the relevant cache names from the very same cache manager:
CacheManager cacheManager = new SimpleCacheManager();
Collection<String> cacheNames = cacheManager.getCacheNames();
cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
If you just want to evict a single cache entry you could either do it programmatically like:
cacheManager.getCache(cacheName).evict(cacheKey);
or annotation-based like
@CacheEvict(value = "yourCacheName", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) {
}
@CacheEvict(value = "yourCacheName", allEntries = true)
public void evictAllCacheValues() {
}
Upvotes: 2