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
forContextRefreshedEvent
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()); }
}
3
Answers
I was successfully able to clear the cache with
ApplicationReadyEvent
. As theCacheManager
bean is available by the time, the cache is getting cleared properly on startupFor the Redis cache manager, if you want to clear the cache on boot, I think you will need to initialize the cache manager with a set of names. See the RedisCacheManagerBuilder docs
For example:
Then you should be able to use
@PostConstruct
in you cache config class, for example.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.