Spring Boot 实现缓存预热
- 1、使用启动监听事件实现缓存预热。
- 2、使用 @PostConstruct 注解实现缓存预热。
- 3、使用 CommandLineRunner 或 ApplicationRunner 实现缓存预热。
- 4、通过实现 InitializingBean 接口,并重写 afterPropertiesSet 方法实现缓存预热。
1、使用启动监听事件实现缓存预热。
使用 ApplicationListener 监听 ContextRefreshedEvent 或 ApplicationReadyEvent 等应用上下文初始化完成事件。
@Component
public class CacheWarmer implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}
@Component
public class CacheWarmer implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}
2、使用 @PostConstruct 注解实现缓存预热。
@Component
public class CachePreloader {
    
    @Autowired
    private YourCacheManager cacheManager;
    @PostConstruct
    public void preloadCache() {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}
3、使用 CommandLineRunner 或 ApplicationRunner 实现缓存预热。
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}

4、通过实现 InitializingBean 接口,并重写 afterPropertiesSet 方法实现缓存预热。
@Component
public class CachePreloader implements InitializingBean {
    @Autowired
    private YourCacheManager cacheManager;
    @Override
    public void afterPropertiesSet() throws Exception {
        // 执行缓存预热业务...
        cacheManager.put("key", dataList);
    }
}



















