如何根据传递的Cache Name逐出Cache

问题描述 投票:0回答:1

我正在调用fetchCatchAndClear方法,我传递List,它包含缓存名称。有人可以帮助我如何迭代列表并根据来自List of String的Cache Name清除缓存。此外,如果列表为空,我应该清除所有缓存。

spring-boot caching spring-cache
1个回答
1
投票

坚持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() {
}
© www.soinside.com 2019 - 2024. All rights reserved.