我正在调用fetchCatchAndClear方法,我传递List,它包含缓存名称。有人可以帮助我如何迭代列表并根据来自List of String的Cache Name清除缓存。此外,如果列表为空,我应该清除所有缓存。
坚持org.springframework.cache.CacheManager
的一个相当简单的方法可能如下:
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());
除非必须从同一个缓存管理器中查询相关的缓存名称,否则驱逐所有缓存也很简单:
CacheManager cacheManager = new SimpleCacheManager();
Collection<String> cacheNames = cacheManager.getCacheNames();
cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
如果您只想逐出一个缓存条目,您可以通过编程方式执行此操作:cacheManager.getCache(cacheName).evict(cacheKey);
或基于注释的类似
@CacheEvict(value = "yourCacheName", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) {
}
@CacheEvict(value = "yourCacheName", allEntries = true)
public void evictAllCacheValues() {
}