缓存预热是指在 Spring Boot 项目启动时,预先将数据加载到缓存系统(如 Redis)中的一种机制。
这里我给大家总结几个缓存预热的方案。
可以使用 ApplicationListener 监听 ContextRefreshedEvent 或 ApplicationReadyEvent 等应用上下文初始化完成事件,在这些事件触发后执行数据加载到缓存的操作。
监听 ContextRefreshedEvent事件
@Component public class CacheWarmer implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { // 执行缓存预热业务... cacheManager.put("key", dataList); } } 或监听 ApplicationReadyEvent 事件
@Component public class CacheWarmer implements ApplicationListener { @Override public void onApplicationEvent(ApplicationReadyEvent event) { // 执行缓存预热业务... cacheManager.put("key", dataList); } } 在需要进行缓存预热的类上添加 @Component 注解,并在其方法中添加 @PostConstruct 注解和缓存预热的业务逻辑,具体实现代码如下:
@Component public class CachePreloader { @Autowired private YourCacheManager cacheManager; @PostConstruct public void preloadCache() { // 执行缓存预热业务... cacheManager.put("key", dataList); } } CommandLineRunner 和 ApplicationRunner 都是 Spring Boot 应用程序启动后要执行的接口,它们都允许我们在应用启动后执行一些自定义的初始化逻辑,例如缓存预热。
CommandLineRunner 实现:
@Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 执行缓存预热业务... cacheManager.put("key", dataList); } } ApplicationRunner 实现示例:
@Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // 执行缓存预热业务... cacheManager.put("key", dataList); } } 注意:CommandLineRunner 和 ApplicationRunner 区别:
实现 InitializingBean 接口并重写 afterPropertiesSet 方法,可以在 Spring Bean 初始化完成后执行缓存预热。
代码如下:
@Component public class CachePreloader implements InitializingBean { @Autowired private YourCacheManager cacheManager; @Override public void afterPropertiesSet() throws Exception { // 执行缓存预热业务... cacheManager.put("key", dataList); } } 推荐:
所以比较推荐后两种方案。