前言
之前有幸跟公司大神聊Spring Boot,大神跟我聊了很多关于Spring Boot相关的知识,其中有一个就是Spring Boot框架下批处理的解决方案,考虑到批处理在实际应用场景中使用率还是有的,好奇的我,决定拿下它!项目代码已上传Git Hub,欢迎取阅:批处理框架
Spring Batch是一款基于 Spring 的企业批处理应用框架,可以帮助我们构建出健壮的批处理应用。实现批处理的整体步骤添加依赖;
Spring Boot基本概念介绍;
编写批处理过程代码;
批处理任务调度;1. 添加依赖;
在项目pom.xml文件的dependencies节点下添加以下依赖:
org.springframework.boot
spring-boot-starter-batch
2. Spring Boot基本概念介绍;
在实现批处理之前我们需要了解一些Spring Batch的基本概念:
1). Item Reader;
表示对资源的读处理,如从数据库查询、从文件读取、从变量读取等;
2). Item Processor;
表示对读取的数据进行处理,开发者可以实现自己的业务逻辑操作来对数据处理,如对数据进行计算、逻辑处理、格式转换等;
3). Item Writer;
表示对资源的写处理,如写入数据库、写入文件、打印log等;
4). Step;
代表一个完整的批处理步骤,一个Step由Item Reader、 Item Processor、Item Writer三部分组成;Step与Item Reader、 Item Processor、Item Writer的关系:
5). Job;
代表一个完整的批处理过程,一个Job由一个或多个Step组成:Job与Step的关系:
批处理过程整体结构:
6). Listener;
监听。Spring Batch中还有个监听的功能,与其他地方的监听类似,用于对Step、Job状态进行监听,我们可以实现监听方法,对其进行一些逻辑处理,如打印log等;
7). JobLauncher;
JobLauncher负责启动job;3. 编写批处理过程代码;
假设我们要解决的问题是,批量读取数组中的数据,并对数据做一些后续的处理。我会写2个Job,一个是单个Step的Job,一个是2个Step的Job,并且2个Step的Job,第1个Step的处理后的数据要给第2个Step使用。
过程代码的整体步骤:
1). 编写ItemReader;
2). 编写ItemProcessor;
3). 编写ItemWriter;
4). 编写JobExecutionListener;
5). 装配Job;
6). 使用数据库源;
7). 修改Spring Boot入口类;
1). 编写ItemReader;ItemReaderServicepackage com.github.dylanz666.service;
import org.springframework.batch.item.ItemReader;
import org.springframework.stereotype.Service;
/**
* @author : dylanz
* @since : 08/25/2020
*/
@Service
public class ItemReaderService implements ItemReader {
//在此处进行数据读取操作,如从数据库查询、从文件中读取、从变量中读取等,本例从变量中读取;
private String[] message = {"message 1", "message 2", "message 3", "message 4", "message 5"};
private int count = 0;
public String read() throws Exception {
if (count < message.length) {
return message[count++];
}
count = 0;
return null;
}
}ItemReaderService2package com.github.dylanz666.service;
import org.springframework.batch.item.ItemReader;
import org.springframework.stereotype.Service;
/**
* @author : dylanz
* @since : 08/26/2020
*/
@Service
public class ItemReaderService2 implements ItemReader {
private int count = 0;
public String read() throws Exception {
if (ItemProcessorService.message != null && count < ItemProcessorService.me