首页 > 解决方案 > 在 Spring Boot 应用程序启动时清除 Redis 缓存

问题描述

在应用程序(spring boot 服务)启动时,需要清除 Redis 缓存。

Redis 在具有自己的卷映射的不同 docker 容器中运行。由于它保留了旧缓存,因此即使在应用程序重新启动后,应用程序也会从 Redis 缓存而不是数据库中选择数据

标签: springspring-bootcachingredis

解决方案


我成功地能够清除缓存ApplicationReadyEvent。由于CacheManagerbean 是可用的,缓存在启动时被正确清除

@Autowired
private CacheManager cacheManager;

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

推荐阅读