Search code examples
javacachingredisspring-data-redis

RedisCacheManager set expires certain time


I just started using RedisCacheManager, is there a way to set the cache to expire at a certain time, like midnight for example?

I can set the cache expiration for one day for example and everything works fine but I would like to make the cache expire at a certain time.

Thanks!


Solution

  • I found a work-around using a scheduled task (spring), but an annotation would be best:

    @Autowired
    public ClearCacheTask(final @NotNull CacheManager cacheManager) {
      this.cacheManager = cacheManager;
    }
    
    @Scheduled(cron="0 0 0 * * ?")
    @Async
    public void resetCacheMidnight() {
      logger.info("Cron Task resetCacheMidnight(), clearing following caches...");
    
      cacheManager.getCacheNames().parallelStream().forEach(name ->  {
        cacheManager.getCache(name).clear();
    
        logger.info("...{} cache cleared", name);
      });      
    }