如何在Spring Boot中逐出所有缓存? [英] How can I evict ALL cache in Spring Boot?

查看:530
本文介绍了如何在Spring Boot中逐出所有缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在app开始时,我初始化了~20个不同的缓存:

On app start, I initialized ~20 different caches:

@Bean
public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(many many names));
    return cacheManager;
}

我想以一定间隔重置所有缓存,比如说每小时。使用计划任务:

I want to reset all the cache at an interval, say every hr. Using a scheduled task:

@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 要求我实际提供缓存的名称,这可能会变得混乱。

Unless I'm reading the docs wrong, but @CacheEvict requires me to actually supply the name of the cache which can get messy.

如何我可以使用 @CacheEvict 来清除所有缓存吗?

How can I use @CacheEvict to clear ALL caches?

我在考虑而不是使用 @CacheEvict ,我只是循环遍历所有缓存:

I was thinking instead of using @CacheEvict, I just loop through all the caches:

cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear());


推荐答案

我刚使用计划任务清除所有缓存缓存管理器。

I just used a scheduled task to clear all cache using the cache manager.

@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());
    }
}

完成工作。

这篇关于如何在Spring Boot中逐出所有缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆