【问题标题】:Clear Redis Cache on Spring Boot Application Startup在 Spring Boot 应用程序启动时清除 Redis 缓存
【发布时间】:2020-04-23 10:44:33
【问题描述】:

应用(spring boot service)启动时,需要清空Redis缓存。

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

  • ContextRefreshedEvent 尝试了@EventListener,但它永远不会被调用。
  • 尝试在 ApplicationMain 类中使用 @PostConstruct,但它没有清除缓存。
  • 尝试使用@CacheEvict(allEntries = true),但仍然没有成功

    @组件 公共类 ApplicationStartUp {

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

    }

【问题讨论】:

  • 您是否验证过 onApplicationEvent 确实被触发并且您能够在循环中获取缓存值。 ?
  • 如果您打印cacheManager.getCacheNames() 的结果,您是否看到您的缓存名称?缓存管理器可能在启动时不返回任何内容。作为测试,尝试使用@PostConstructcacheManger.getCache("your cache").clear()

标签: spring spring-boot caching redis


【解决方案1】:

我成功地使用ApplicationReadyEvent 清除了缓存。由于CacheManager bean 是可用的,缓存在启动时被正确清除

@Autowired
private CacheManager cacheManager;

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

【讨论】:

  • 你能给我提供你的cacheconfig类吗?我正在实施与此类似的事情,但仍然面临一些问题。
  • 您是否获取所有缓存数据,因为 cacheManager.getCacheNames() 不返回缓存数据。你怎么样了?
【解决方案2】:

对于 Redis 缓存管理器,如果你想在启动时清除缓存,我认为你需要用一组名称来初始化缓存管理器。见RedisCacheManagerBuilder docs

例如:

RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
                        .initialCacheNames(Set.of("cacheOne", "cacheTwo"))
                        .build();

例如,您应该可以在缓存配置类中使用@PostConstruct

@PostConstruct
public void clearCache() {
    cacheManager.getCacheNames()
                .parallelStream()
                .forEach(n -> cacheManager.getCache(n).clear());
}

【讨论】:

  • 感谢您的建议。但是我将 ContextRefreshedEvent 侦听器更改为 ApplicationReadyEvent 侦听器,它工作正常
  • @Senthil Cool,也感谢您发布您的解决方案。
  • 不初始化缓存名称是否可以清除缓存?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
相关资源
最近更新 更多