在应用启动时,我初始化了约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清除所有缓存?
我在想而不是使用 @CacheEvict,而是循环遍历所有缓存:
cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());
我只是使用计划任务来使用缓存管理器清除所有缓存。
@Component public class ClearCacheTask { @Autowired private CacheManager cacheManager; @Scheduled(fixedRateString = "${clear.all.cache.fixed.rate}", initialDelayString = "${clear.all.cache.init.delay}") // reset cache every hr, with delay of 1hr after app start public void reportCurrentTime() { cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear()); } }
完成工作。