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已经被完全初始化)被调用,在ApplicationRunnerrun方法执行之前,所有。
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、区别
  • CommandLineRunnerApplicationRunner之后被调用,也是在所有的ApplicationContext上下文都刷新和加载完成后执行。但是,与ApplicationRunner不同的是,CommandLineRunner#run方法执行之前,SpringApplication#run方法的参数也会被作为命令行参数传递给run方法。
  • 如果需要访问命令行参数和选项,或者需要在所有Bean初始化之前执行特定的操作,你可以选择使用ApplicationRunner。如果你只需要在所有Bean初始化之后执行某些操作,你可以使用CommandLineRunner

无论你选择使用ApplicationRunne还是CommandLineRunner,它们都提供了在Spring Boot项目启动时执行自定义逻辑的能力。你可以根据实际需求选择适合的接口来实现项目预热或其他操作。

4、待续

后面的关于参数传递方面的信息,将会持续记录学习

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值