简体   繁体   中英

How can I evict ALL cache in Spring Boot?

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

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

How can I use @CacheEvict to clear ALL caches?

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

Gets the job done.

Below evictCache method evicts fooCache using @CacheEvict annotation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM