Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Redis Cache on Spring Boot Application Startup

On application (spring boot service) startup, need to clear the Redis cache.

Redis is running in a different docker container with own volume mapping. Since it retains the old cache, the application picks the data from Redis cache instead of Database even after the application restarts

  • Tried @EventListener for ContextRefreshedEvent and it is never getting called.
  • Tried with @PostConstruct in ApplicationMain class, but it doesn't clear the cache.
  • Tried using @CacheEvict(allEntries = true), but still no luck

    @Component public class ApplicationStartUp {

    @Autowired
    private CacheManager cacheManager;
    
    @EventListener()
    public void onApplicationEvent(ContextStartedEvent event) {
        cacheManager.getCacheNames()
                    .parallelStream()
                    .forEach(n -> cacheManager.getCache(n).clear());
    }
    

    }

like image 336
Senthil Avatar asked Aug 31 '26 06:08

Senthil


2 Answers

I was successfully able to clear the cache with ApplicationReadyEvent. As the CacheManager bean is available by the time, the cache is getting cleared properly on startup

@Autowired
private CacheManager cacheManager;

@EventListener
public void onApplicationEvent(ApplicationReadyEvent event) {
    cacheManager.getCacheNames()
                .parallelStream()
                .forEach(n -> cacheManager.getCache(n).clear());
}
like image 151
Senthil Avatar answered Sep 02 '26 22:09

Senthil


A simple practice to clear Redis DB at earlier life cycle stage. To config CacheManager @bean with argument RedisConnectionFactory passed in, calling flushDb() to delete all keys of the currently selected database before build up.

 @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        redisConnectionFactory.getConnection().flushDb(); //Delete all keys of the currently selected database
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()).build();
    }
like image 22
MEI Liao Avatar answered Sep 02 '26 22:09

MEI Liao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!