SpringBoot程序预装载数据
简介
在项目实际的开发过程中,有时候会遇到需要在应用程序启动完毕对外提供服务之前预先将部分数据装载到缓存的需求。本文就总结了常见的数据预装载方式及其实践。
适用场景
- 预装载应用级别数据到缓存:如字典数据、公共的业务数据
- 系统预热
- 心跳检测:如在系统启动完毕访问一个外服务接口等场景
常见方式
- 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程序预装载数据的更多相关文章
- [十五]SpringBoot 之 启动加载数据
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...
- DHTMLX 前端框架 建立你的一个应用程序 教程(六)-- 表格加载数据
从数据库加载数据 这篇我们介绍从MySQL数据库中加载数据到表格 我们使用 MySql的数据库dhtmlx_tutorial 和表contacts 示例使用的是PHP平台和dhtmlxConnecto ...
- 微信小程序(五) 利用模板动态加载数据
利用模板动态加载数据,其实是对上一节静态数据替换成动态数据:
- Android应用程序后台加载数据
从ContentProvider查询你需要显示的数据是比较耗时的.如果你在Activity中直接执行查询的操作,那么有可能导致Activity出现ANR的错误.即使没有发生ANR,用户也容易感知到一个 ...
- SpringBoot(七)-- 启动加载数据
一.场景 实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求.为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunn ...
- 微信小程序下拉刷新 并重新加载数据
1.在json页面配置: { "enablePullDownRefresh": true } 2.调用刷新函数 onPullDownRefresh: function() { wx ...
- Spring Boot 启动加载数据 CommandLineRunner
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...
- 十三、 Spring Boot 启动加载数据 CommandLineRunner
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...
- 第一个SpringBoot程序
第一个SpringBoot程序 例子来自慕课网廖师兄的免费课程 2小时学会SpringBoot Spring Boot进阶之Web进阶 使用IDEA新建工程,选择Spring Initializr,勾 ...
随机推荐
- Scanner几个问题与正则简介
Pre:最近做了头条的在线笔试,对Scanner输入的处理有些特殊,当时是一脸懵逼态,遂由此随笔(/@_@\),java小白,有错难免! 查了下Scanner的源码,没有头绪,但是其中用到了正则的知识 ...
- 一个".java"源文件中是否可以包含多个类(不是内部类)?有什么限制?
可以,但一个源文件中最多只能有一个公开类(public class)而且文件名必须和公开类的类名完全保持一致.
- memcached 最大能存储多大的单个 item?
1MB.如果你的数据大于 1MB,可以考虑在客户端压缩或拆分到多个 key 中. 为什么单个 item 的大小被限制在 1M byte 之内? 简单的回答:因为内存分配器的算法就是这样的. 详细的回答 ...
- Java 中 WeakReference 与 SoftReference 的区别?
虽然 WeakReference 与 SoftReference 都有利于提高 GC 和 内存的效率, 但是 WeakReference ,一旦失去最后一个强引用,就会被 GC 回收,而软引用 虽然不 ...
- js里面是没有Trim()这个方法的可以用以下的形式来判断是否输入的值为空
if (text.value.replace(/\s+/g, "").length == 0)
- springboot使用自定义注解和反射实现一个简单的支付
优点: 未使用if else,就算以后增加支付类型,也不用改动之前代码 只需要新写一个支付类,给添加自定义注解@Pay 首先: 定义自定义注解 Pay 定义 CMBPay ICBCPay 两种支付 根 ...
- 编译器警告c4996
由于编译器的原因(我用的是vs 2012),我们写程序时有时候会遇到编译器给出的警告,如: warning C4996: 'fopen': This function or variable may ...
- css3 弹性布局和多列布局
弹性盒子基础 弹性盒子(Flexible Box)是css3中盒子模型的弹性布局,在传统的布局方式上增加了很多灵活性. 定义一个弹性盒子 在父盒子上定义display属性: #box{ display ...
- 《每周一点canvas动画》——3D点线与水波动画
<每周一点canvas动画>--差分函数的妙用 每周一点canvas动画代码文件 好像上次更新还是十一前,这唰唰唰的就过去大半个月了,现在才更新实在不好意思.这次我们不涉及canvas 3 ...
- 深入理解ES6之《用模块封装代码》
什么是模块 模块是自动运行在严格模式下并且没有办法退出运行的Javascript代码 在模块的顶部this的值是undefined 其模块不支持html风格的代码注释除非用default关键字,否则不 ...