SpringBoot实现数据预热的方式小结
Springboot如何实现数据预热
这里用到的数据预热,就是在项目启动时将一些数据量较大的数据加载到缓存中(笔者这里用的Redis)。那么在项目启动有哪些方式可以实现数据预热呢?
1、方式一:ApplicationRunner接口
package org.springframework.boot;
@FunctionalInterface
public interface ApplicationRunner {
/**
* 用于运行Bean的回调。
* @param 参数传入的应用程序参数
* @throws 出错时出现异常
*/
void run(ApplicationArguments args) throws Exception;
}ApplicationRunner接口的run方法:
void run(ApplicationArguments args) throws Exception;
1、ApplicationRunner在所有的ApplicationContext上下文都刷新和加载完成后(Spring Bean已经被完全初始化)被调用,在ApplicationRunner的run方法执行之前,所有。
2、在ApplicationRunner中,可以直接通过 ApplicationArguments对象来获取命令行参数和选项。
实现接口
@Component
public class DataPreloader implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(DataPreloader.class);
@Override
public void run(ApplicationArguments args) {
log.info("数据预热启动, 这里会在系统启动后执行"));
}
}2、方式二:CommandLineRunner接口
package org.springframework.boot;
@FunctionalInterface
public interface CommandLineRunner {
/**
* 用于运行Bean的回调。
* @param Args传入的Main方法参数
* @throws 出错时出现异常
*/
void run(String... args) throws Exception;
}CommandLineRunner接口的run方法:
void run(String... args) throws Exception;
1、在CommandLineRunner中,命令行参数将以字符串数组的形式传递给
run方法。
实现接口
@Component
public class DataPreloader2 implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(DataPreloader2.class);
@Override
public void run(String... args){
log.info("数据预热启动, 这里会在系统启动后执行");
}
}3、区别
- CommandLineRunner在ApplicationRunner之后被调用,也是在所有的ApplicationContext上下文都刷新和加载完成后执行。但是,与ApplicationRunner不同的是,CommandLineRunner#run方法执行之前,SpringApplication#run方法的参数也会被作为命令行参数传递给run方法。
- 如果需要访问命令行参数和选项,或者需要在所有Bean初始化之前执行特定的操作,你可以选择使用ApplicationRunner。如果你只需要在所有Bean初始化之后执行某些操作,你可以使用CommandLineRunner。
无论你选择使用ApplicationRunne还是CommandLineRunner,它们都提供了在Spring Boot项目启动时执行自定义逻辑的能力。你可以根据实际需求选择适合的接口来实现项目预热或其他操作。
以上就是SpringBoot实现数据预热的方式小结的详细内容,更多关于SpringBoot数据预热的资料请关注脚本之家其它相关文章!
相关文章
Mybatis-plus使用TableNameHandler分表详解(附完整示例源码)
这篇文章主要介绍了Mybatis-plus使用TableNameHandler分表详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-01-01
JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别
这篇文章主要介绍了JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们来一起学习下吧2019-07-07
SpringMVC @RequestBody 为null问题的排查及解决
这篇文章主要介绍了SpringMVC @RequestBody 为null问题的排查及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-10-10


最新评论