spring - 在 Spring Boot 应用程序启动时清除 Redis 缓存
问题描述
在应用程序(spring boot 服务)启动时,需要清除 Redis 缓存。
Redis 在具有自己的卷映射的不同 docker 容器中运行。由于它保留了旧缓存,因此即使在应用程序重新启动后,应用程序也会从 Redis 缓存而不是数据库中选择数据
- 尝试
@EventListener
过ContextRefreshedEvent
,它永远不会被调用。 - 在 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()); }
}
解决方案
我成功地能够清除缓存ApplicationReadyEvent
。由于CacheManager
bean 是可用的,缓存在启动时被正确清除
@Autowired
private CacheManager cacheManager;
@EventListener
public void onApplicationEvent(ApplicationReadyEvent event) {
cacheManager.getCacheNames()
.parallelStream()
.forEach(n -> cacheManager.getCache(n).clear());
}
推荐阅读
- python-3.x - 如何使用 python 和 pyzbar 检测二维码
- jenkins - 我如何实现语义版本控制
- php - PHP `error_reporting` 的默认值是多少?
- r - R中性别过剩的人口金字塔
- c# - MS Graph OneNote 获取 Section displayName
- awk - 如何使用 awk 将 2 个文件合并为第三个文件?
- android - 带有对象问题的 Kotlin 单例
- typescript - 输入“观察者”
[]' 不可分配给类型“观察者” []' - powerbi - Power BI - 如何动态排除某些行?我总是想要一种类型的行,但想要 col1=A 或 B 的任何一行,而不是两者
- c# - 根据结构列表上的条件查找 FirstOrDefault