【发布时间】: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()的结果,您是否看到您的缓存名称?缓存管理器可能在启动时不返回任何内容。作为测试,尝试使用@PostConstruct和cacheManger.getCache("your cache").clear()。
标签: spring spring-boot caching redis