Java 如何在 Spring Boot 中驱逐所有缓存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38358664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:14:08  来源:igfitidea点击:

How can I evict ALL cache in Spring Boot?

javacachingspring-boot

提问by iCodeLikeImDrunk

On app start, I initialized ~20 different caches:

在应用程序启动时,我初始化了大约 20 个不同的缓存:

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

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

除非我读错了文档,但 @CacheEvict要求我实际提供可能会变得混乱的缓存名称。

How can I use @CacheEvictto clear ALL caches?

如何使用 @CacheEvict清除所有缓存?

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

我在想而不是使用 @CacheEvict,我只是遍历所有缓存:

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

采纳答案by iCodeLikeImDrunk

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

Gets the job done.

完成工作。

回答by Kt Mack

Below evictCache method evicts fooCache using @CacheEvict annotation.

下面的 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.");
  }
}