在app开始时,我初始化了~20个不同的缓存:
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(many many names));
return cacheManager;
}
我希望每隔一小时重置一次所有缓存。使用计划任务:
@Component
public class ClearCacheTask {
private static final Logger logger = LoggerFactory.getLogger(ClearCacheTask.class);
private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
@Value("${clear.all.cache.flag}")
private String clearAllCache;
private CacheManager cacheManager;
@CacheEvict(allEntries = true, value="...............")
@Scheduled(fixedRate = 3600000, initialDelay = 3600000) // reset cache every hr, with delay of 1hr
public void reportCurrentTime() {
if (Boolean.valueOf(clearAllCache)) {
logger.info("Clearing all cache, time: " + formatter.print(DateTime.now()));
}
}
}
除非我正在阅读文档错误,但@CacheEvict
要求我实际提供缓存的名称,这可能会变得混乱。
如何使用@CacheEvict
清除所有缓存?
我在思考而不是使用@CacheEvict
,我只是循环遍历所有缓存:
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
答案 0 :(得分:2)
在evictCache方法下面使用@CacheEvict注释驱逐fooCache。
public class FooService {
@Autowired
private FooRespository repository;
@Cacheable("fooCache")
public List<Foo> findAll() {
return repository.findAll();
}
@CacheEvict(value="fooCache",allEntries=true)
public void evictCache() {
LogUtil.log("Evicting all entries from fooCache.");
}
}