Spring Boot 应用程序启动时清除 Redis 缓存

Sen*_*hil 4 spring caching redis spring-boot

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

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

  • 尝试@EventListenerContextRefreshedEvent但从未被调用过。
  • 尝试在 ApplicationMain 类中使用@PostConstruct,但它不会清除缓存。
  • 尝试使用@CacheEvict(allEntries = true),但仍然没有运气

    @Component 公共类ApplicationStartUp {

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

    }

Sen*_*hil 6

我成功地能够使用 清除缓存ApplicationReadyEvent。由于CacheManagerbean 已可用,因此缓存在启动时会被正确清除

@Autowired
private CacheManager cacheManager;

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