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、待续

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

猜你喜欢

转载自blog.csdn.net/qq_50661854/article/details/132916611