【发布时间】:2019-03-25 15:52:23
【问题描述】:
我在传递 List 的地方调用 fetchCatchAndClear 方法,它由缓存名称组成。有人可以帮助我如何迭代列表并根据来自字符串列表的缓存名称清除缓存。此外,如果列表为空,我应该清除所有存在的缓存。
【问题讨论】:
标签: spring-boot caching spring-cache
我在传递 List 的地方调用 fetchCatchAndClear 方法,它由缓存名称组成。有人可以帮助我如何迭代列表并根据来自字符串列表的缓存名称清除缓存。此外,如果列表为空,我应该清除所有存在的缓存。
【问题讨论】:
标签: spring-boot caching spring-cache
坚持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() {
}
【讨论】:
cacheManager.getCache(cacheName).evict(cacheKey)。对于@CacheEvict,请查看我的更新答案。