简介

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

适用场景

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

常见方式

  • 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. object 转json 相互转换

    1.object 转json 2.json转object 参考   https://blog.csdn.net/justry_deng/article/details/80780175

  2. 高度不定,宽100%,内一div高不确定,如何实现垂直居中?

    verticle-align: middle; 绝对定位50%加translateY(-50%) 绝对定位,上下左右全0,margin:auto

  3. redis 如何做内存优化?

    1.缩减键值对象 缩减键(key)和值(value)的长度, key长度:如在设计键时,在完整描述业务情况下,键值越短越好. value长度:值对象缩减比较复杂,常见需求是把业务对象序列化成二进制数组 ...

  4. spring-boot--lernning之自定义starters

    思路: 1这个场景需要使用到的依赖是什么??? 2如何编写自动配置 @Configuration 指定这个类是一个配置类 @ConditionalOnXXXX 指定条件下成立的情况下自动配置类生效 @ ...

  5. 学习Apache(三)

    对某个目录开启验证登录 <Directory /var/www/html/admin > AllowOverride All Order allow,deny Allow from all ...

  6. Effective Java —— 多字段下考虑使用建造者模式构建实例

    本文参考 本篇文章参考自<Effective Java>第三版第二条"Consider a builder when faced with many constructor pa ...

  7. I2C总线完全版——I2C总线的结构、工作时序与模拟编程

    I2C总线的结构.工作时序与模拟编程 I2C总线的结构.工作时序与模拟编程I2C总线(Inter Integrated Circuit)是飞利浦公司于上个世纪80年代开发的一种"电路板级&q ...

  8. 03. Pandas数据结构

    03. Pandas数据结构 Series DataFrame 从DataFrame中查询出Series 1. Series Series是一种类似于一维数组的对象,它由一组数据(不同数据类型)以及一 ...

  9. Flex 布局新旧混合写法详解(兼容微信)

    flex 是个非常好用的属性,如果说有什么可以完全代替 float 和 position ,那么肯定是非它莫属了(虽然现在还有很多不支持 flex 的浏览器).然而国内很多浏览器对 flex 的支持都 ...

  10. Android地图化实现

    今天在Android上实现了地图化,可以通过记录用户位置和体温是否异常来实现地图区域变色,并显示正常人数,与体温是否异常,且可以地图下钻. 效果展示: