• Springboot如何实现数据预热


    Springboot如何实现数据预热

    这里用到的数据预热,就是在项目启动时将一些数据量较大的数据加载到缓存中(笔者这里用的Redis)。那么在项目启动有哪些方式可以实现数据预热呢?

    1、方式一:ApplicationRunner接口
    package org.springframework.boot;
    
    @FunctionalInterface
    public interface ApplicationRunner {
    	/**
    	 * 用于运行Bean的回调。
    	 * @param 参数传入的应用程序参数
    	 * @throws 出错时出现异常
    	 */
    	void run(ApplicationArguments args) throws Exception;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ApplicationRunner接口的run方法:

    void run(ApplicationArguments args) throws Exception;
    
    • 1

    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("数据预热启动, 这里会在系统启动后执行"));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    2、方式二:CommandLineRunner接口
    package org.springframework.boot;
    
    @FunctionalInterface
    public interface CommandLineRunner {
    	/**
    	 * 用于运行Bean的回调。
    	 * @param Args传入的Main方法参数
    	 * @throws 出错时出现异常
    	 */
    	void run(String... args) throws Exception;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    CommandLineRunner接口的run方法:

    void run(String... args) throws Exception;
    
    • 1

    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("数据预热启动, 这里会在系统启动后执行");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    3、区别
    • CommandLineRunnerApplicationRunner之后被调用,也是在所有的ApplicationContext上下文都刷新和加载完成后执行。但是,与ApplicationRunner不同的是,CommandLineRunner#run方法执行之前,SpringApplication#run方法的参数也会被作为命令行参数传递给run方法。
    • 如果需要访问命令行参数和选项,或者需要在所有Bean初始化之前执行特定的操作,你可以选择使用ApplicationRunner。如果你只需要在所有Bean初始化之后执行某些操作,你可以使用CommandLineRunner

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

    4、待续

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

  • 相关阅读:
    Echarts绘制Tree树图的涟漪效果effectScatter
    耗时三年整理出来的软件测试项目实操指南与过程文档
    【深蓝学院】手写VIO第1章第1节
    大数据运维实战第五课 手动模式构建双 Namenode+Yarn 的 Hadoop 集群(上)
    MySQL 表的增删查改(基础)
    大语言模型(LLM)工作的3个步骤,一文带你搞清楚!
    study
    vite3、vue 项目打包分包进阶-组件分包
    浅析Redis基础数据结构
    Minio分布式存储入门(使用新版本)
  • 原文地址:https://blog.csdn.net/qq_50661854/article/details/132916611