简介

在项目实际的开发过程中,有时候会遇到需要在应用程序启动完毕对外提供服务之前预先将部分数据装载到缓存的需求。本文就总结了常见的数据预装载方式及其实践。

适用场景

  • 预装载应用级别数据到缓存:如字典数据、公共的业务数据
  • 系统预热
  • 心跳检测:如在系统启动完毕访问一个外服务接口等场景

常见方式

  • ApplicationEvent
  • CommandLineRunner
  • ApplicationRunner

ApplicationEvent

应用程序事件,就是发布订阅模式。在系统启动完毕,向应用程序注册一个事件,监听者一旦监听到了事件的发布,就可以做一些业务逻辑的处理了。

既然是发布-订阅模式,那么订阅者既可以是一个,也可以是多个。

定义event


import org.springframework.context.ApplicationEvent;
public class CacheEvent   extends ApplicationEvent {
    public CacheEvent(Object source) {
        super(source);
    }
}

定义listener


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Component
public class CacheEventListener implements ApplicationListener<CacheEvent> {
    @Autowired
    private MaskingService maskingService;
    @Autowired
    private RedisCache redisCache;
    @Override
    public void onApplicationEvent(CacheEvent cacheEvent) {
        log.debug("CacheEventListener-start");
        List<SysMasking> maskings = maskingService.selectAllSysMaskings();
        if (!CollectionUtils.isEmpty(maskings)) {
            log.debug("CacheEventListener-data-not-empty");
            Map<String, List<SysMasking>> cacheMap = maskings.stream().collect(Collectors.groupingBy(SysMasking::getFieldKey));
            cacheMap.keySet().forEach(x -> {
                if (StringUtils.isNotEmpty(x)) {
                    log.debug("CacheEventListener-x={}", x);
                    List<SysMasking> list = cacheMap.get(x);
                    long count = redisCache.setCacheList(RedisKeyPrefix.MASKING.getPrefix() + x, list);
                    log.debug("CacheEventListener-count={}", count);
                } else {
                    log.debug("CacheEventListener-x-is-empty");
                }
            });
        } else {
            log.debug("CacheEventListener-data-is-empty");
        }
        log.debug("CacheEventListener-end");
    }
}

注册event


@Slf4j
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class BAMSApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BAMSApplication.class, args);
        log.debug("app-started");
        context.publishEvent(new CacheEvent("处理缓存事件"));
    }
}

CommandLineRunner

通过实现 CommandLineRunner 接口,可以在应用程序启动完毕,回调到指定的方法中。


package com.ramble.warmupservice.runner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class CacheCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.debug("CacheCommandLineRunner-start");
        log.debug("CacheCommandLineRunner-参数={}", args);
        // 注入业务 service ,获取需要缓存的数据
        // 注入 redisTemplate ,将需要缓存的数据存放到 redis 中
        log.debug("CacheCommandLineRunner-end");
    }
}

ApplicationRunner

同CommandLineRunner 类似,区别在于,对参数做了封装。


package com.ramble.warmupservice.runner;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class CacheApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("CacheApplicationRunner-start");
        log.debug("CacheApplicationRunner-参数={}", JSON.toJSONString(args));
        // 注入业务 service ,获取需要缓存的数据
        // 注入 redisTemplate ,将需要缓存的数据存放到 redis 中
        log.debug("CacheApplicationRunner-end");
    }
}

测试

上述代码在idea中启动,若不带参数,输出如下:


2022-04-28 15:44:00.981  INFO 1160 --- [           main] c.r.w.WarmupServiceApplication           : Started WarmupServiceApplication in 1.335 seconds (JVM running for 2.231)
2022-04-28 15:44:00.982 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-start
2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-参数={"nonOptionArgs":[],"optionNames":[],"sourceArgs":[]}
2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-end
2022-04-28 15:44:01.025 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-start
2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-参数={}
2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-end
2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-start
2022-04-28 15:44:01.026 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-参数=ApplicationEvent-->缓存系统数据
2022-04-28 15:44:01.029 DEBUG 1160 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-end
Disconnected from the target VM, address: '127.0.0.1:61320', transport: 'socket'
Process finished with exit code 130

若使用 java -jar xxx.jar --server.port=9009 启动,则输入如下:


2022-04-28 16:02:05.327  INFO 9916 --- [           main] c.r.w.WarmupServiceApplication           : Started WarmupServiceApplication in 1.78 seconds (JVM running for 2.116)
2022-04-28 16:02:05.329 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-start
2022-04-28 16:02:05.393 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-参数={"nonOptionArgs":[],"optionNames":["server.port"],"sourceArgs":["--server.port=9009"]}
2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheApplicationRunner      : CacheApplicationRunner-end
2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-start
2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-参数=--server.port=9009
2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.runner.CacheCommandLineRunner      : CacheCommandLineRunner-end
2022-04-28 16:02:05.395 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-start
2022-04-28 16:02:05.396 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener- 参数=ApplicationEvent-->缓存系统数据
2022-04-28 16:02:05.396 DEBUG 9916 --- [           main] c.r.w.listener.CacheEventListener        : CacheEventListener-end

执行顺序

从上面测试的输出,可以看到三种方式执行的顺序为:

ApplicationRunner--->CommandLineRunner--->ApplicationEvent

另外,若同时定义多个runner,可以通过order来指定他们的优先级。

代码

https://gitee.com/naylor_personal/ramble-spring-cloud/tree/master/warmup-service

SpringBoot程序预装载数据的更多相关文章

  1. [十五]SpringBoot 之 启动加载数据

    实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...

  2. DHTMLX 前端框架 建立你的一个应用程序 教程(六)-- 表格加载数据

    从数据库加载数据 这篇我们介绍从MySQL数据库中加载数据到表格 我们使用 MySql的数据库dhtmlx_tutorial 和表contacts 示例使用的是PHP平台和dhtmlxConnecto ...

  3. 微信小程序(五) 利用模板动态加载数据

    利用模板动态加载数据,其实是对上一节静态数据替换成动态数据:

  4. Android应用程序后台加载数据

    从ContentProvider查询你需要显示的数据是比较耗时的.如果你在Activity中直接执行查询的操作,那么有可能导致Activity出现ANR的错误.即使没有发生ANR,用户也容易感知到一个 ...

  5. SpringBoot(七)-- 启动加载数据

    一.场景 实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求.为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunn ...

  6. 微信小程序下拉刷新 并重新加载数据

    1.在json页面配置: { "enablePullDownRefresh": true } 2.调用刷新函数 onPullDownRefresh: function() { wx ...

  7. Spring Boot 启动加载数据 CommandLineRunner

    实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...

  8. 十三、 Spring Boot 启动加载数据 CommandLineRunner

    实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...

  9. 第一个SpringBoot程序

    第一个SpringBoot程序 例子来自慕课网廖师兄的免费课程 2小时学会SpringBoot Spring Boot进阶之Web进阶 使用IDEA新建工程,选择Spring Initializr,勾 ...

随机推荐

  1. mysql join 底层原理

    你知道 Sql 中 left join 的底层原理吗? 2019-09-10阅读 7130 https://cloud.tencent.com/developer/column/2367   01.前 ...

  2. Java IO流处理

    字节流是由字节组成的;字符流是由字符组成的Java里字符由两个字节组成. 1字符=2字节JAVA中的字节流是采用ASCII编码的,字符流是采用好似UTF编码,支持中文的 Java IO流处理 面试题汇 ...

  3. final, finally, finalize的区别?

    final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承.内部类要访问局部变量,局部变量必须定义成final类型.finally是异常处理语句结构的一部分,表示总是执行.fin ...

  4. Homebrew 卸载后重新安装mysql

    1.卸载https://blog.csdn.net/liuxw1/article/details/81434005 https://jingyan.baidu.com/article/5553fa82 ...

  5. prometheus-存储

    采集到的样本以时间序列的方式保存在内存(TSDB 时序数据库)中,并定时保存到硬盘中 prometheus一般会保留15天 prometheus按照block块的方式来存储数据,每2小时为一个时间单位 ...

  6. 学习heartbeat-05 实现web服务高可用

    一.环境介绍 说明:所有案例在虚拟机(VMware)上完成 操作系统:centos 6.5 64bit 高可用软件:heartbeat 3.0.4 Web应用服务器:apache httpd 2.2. ...

  7. (stm32f103学习总结)—独立看门狗(IWDG)

    一.IWDG介绍 1.1 IWDG简介 STM32F1芯片内部含有两个看门狗外设,一个是独立看门狗IWDG,另 一个是窗口看门狗WWDG.两个看门狗外设(独立和窗口)均可用于检测 并解决由软件错误导致 ...

  8. SCSS学习笔记(一)

    SCSS的由来 SCSS就是加强版的CSS,要讲SCSS那就一定要从SASS讲起 SASS Sass(英文全称:Syntactically Awesome Stylesheets)是一个最初由Hamp ...

  9. 用jq实现移动端滑动轮播以及定时轮播效果

    Html的代码: <div class="carousel_img"> <div class="car_img" style="ba ...

  10. spring原始注解开发-01

    我们使用xml-Bean标签的配置方式和注解做对比理解 1.创建UserDao接口以及UserDao的实现类UserDaoImpl(接口代码省略) public class UserDaoImpl i ...