Spring Batch的核心概念

如下图,JobLancher启动job,一个job包含若干step,每个step又包含一个ItemReader(读数据),ItemProcessor(处理数据),和ItemWriter(输出数据),job的元数据和运行状态则存储在JobRepository中。

Spring batch主要有以下部分组成

  • JobRepository       用来注册job的容器
  • JobLauncher               用来启动Job的接口
  • Job                              实际执行的任务,包含一个或多个Step
  • Step                            step包含ItemReader、ItemProcessor和ItemWriter
  • ItemReader                 用来读取数据的接口
  • ItemProcessor            用来处理数据的接口
  • ItemWriter                   用来输出数据的接口

以上Spring Batch的主要组成部分只需要注册成Spring的Bean即可。若想开启批处理的支持还需在配置类上使用@EnableBatchProcessing,在Spring Batch中提供了大量的ItemReader和ItemWriter的实现,用来读取不同的数据来源,数据的处理和校验都要通过ItemProcessor接口实现来完成。

Job运行时概念

Job的一次完整运行称为一个JobInstance,由JobParameter区分(Spring认为相同的Job不应该多次运行),即如果JobParameter相同则为同一个Job,而一次运行如果中途失败或者抛异常,再次运行仍为一个JobInstance,而其中的每次运行称为一个JobExecution。执行一个step称为StepExecution

关系如下:

Job 1->n JobInstance 1->n JobExecution 1->n StepExecution

JobExecution和StepExecution各包含一个ExecutionContext,其中存储了key-value对,可以用来存储运行状态。

框架实践

下面这个例子实现的是:从变量中读取3个字符串全转化大写并输出到控制台,加了一个监听,当任务完成时输出一个字符串到控制台,通过web端来调用。

版本说明

  • spring-boot:2.0.1.RELEASE
  • spring-batch-4.0.1.RELEASE(Spring-Boot 2.0.1就是依赖的此版本)

POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.javainuse</groupId><artifactId>springboot-batch</artifactId><version>0.0.1</version><packaging>jar</packaging><name>SpringBatch</name><description>Spring Batch-Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version><relativePath /> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-batch</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

Item Reader 

读取:从数组中读取3个字符串

package com.javainuse.step;import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;public class Reader implements ItemReader<String> {private String[] messages = { "javainuse.com", "Welcome to Spring Batch Example","We use H2 Database for this example" };private int count = 0;@Overridepublic String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {if (count < messages.length) {return messages[count++];} else {count = 0;}return null;}}

Item Processor

处理:将字符串转为大写

package com.javainuse.step;import org.springframework.batch.item.ItemProcessor;public class Processor implements ItemProcessor<String, String> {@Overridepublic String process(String data) throws Exception {return data.toUpperCase();}}

Item Writer 

输出:把转为大写的字符串输出到控制台

package com.javainuse.step;import java.util.List;import org.springframework.batch.item.ItemWriter;public class Writer implements ItemWriter<String> {@Overridepublic void write(List<? extends String> messages) throws Exception {for (String msg : messages) {System.out.println("Writing the data " + msg);}}}

 Listener

监听:任务成功完成后往控制台输出一行字符串

package com.javainuse.listener;import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;public class JobCompletionListener extends JobExecutionListenerSupport {@Overridepublic void afterJob(JobExecution jobExecution) {if (jobExecution.getStatus() == BatchStatus.COMPLETED) {System.out.println("BATCH JOB COMPLETED SUCCESSFULLY");}}}

Config 

Spring Boot配置

package com.javainuse.config;import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import com.javainuse.listener.JobCompletionListener;
import com.javainuse.step.Processor;
import com.javainuse.step.Reader;
import com.javainuse.step.Writer;@Configuration
public class BatchConfig {@Autowiredpublic JobBuilderFactory jobBuilderFactory;@Autowiredpublic StepBuilderFactory stepBuilderFactory;@Beanpublic Job processJob() {return jobBuilderFactory.get("processJob").incrementer(new RunIdIncrementer()).listener(listener()).flow(orderStep1()).end().build();}@Beanpublic Step orderStep1() {return stepBuilderFactory.get("orderStep1").<String, String> chunk(1).reader(new Reader()).processor(new Processor()).writer(new Writer()).build();}@Beanpublic JobExecutionListener listener() {return new JobCompletionListener();}}

Controller 

控制器:配置web路由,访问/invokejob来调用任务

package com.javainuse.controller;import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class JobInvokerController {@AutowiredJobLauncher jobLauncher;@AutowiredJob processJob;@RequestMapping("/invokejob")public String handle() throws Exception {JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();jobLauncher.run(processJob, jobParameters);return "Batch job has been invoked";}
}

application.properties 

配置:Spring Batch在加载的时候job默认都会执行,把spring.batch.job.enabled置为false,即把job设置成不可用,应用便会根据jobLauncher.run来执行。下面2行是数据库的配置,不配置也可以,使用的嵌入式数据库h2。

spring.batch.job.enabled=false
spring.datasource.url=jdbc:h2:file:./DB
spring.jpa.properties.hibernate.hbm2ddl.auto=update

Application

Spring Boot入口类:加注解@EnableBatchProcessing

package com.javainuse;import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchApplication {public static void main(String[] args) {SpringApplication.run(SpringBatchApplication.class, args);}
}

进阶

方案一:spring boot上构建spring batch远程分区Step

https://gitee.com/kailing/partitionjob

方案二:spring batch进阶-基于RabbitMQ远程分区Step

http://www.kailing.pub/article/index/arcid/196.html

参考:

https://jamie-wang.iteye.com/blog/1876320

查了十几个帖子总结,如有侵权请联系作者。

Spring Batch 使用指南相关推荐

  1. Spring Batch教程–最终指南

    这是Spring批处理教程,它是Spring框架的一部分. Spring Batch提供了可重用的功能,这些功能对于处理大量记录至关重要,包括日志记录/跟踪,事务管理,作业处理统计信息,作业重新启动, ...

  2. Spring Batch面试终极指南

    问:什么是Spring Batch Admin? 问:在哪里使用批处理? 问:什么是工作步骤? 问:什么是ItemReader? 问:什么是ItemProcessor? 问:什么是Spring Bat ...

  3. 你知道 Spring Batch 吗?

    点击上方"朱小厮的博客",选择"设为星标" 后台回复"加群"加入公众号专属技术群 译者:李东 来源:uee.me/cEwUq 我将向您展示如 ...

  4. 批处理框架 Spring Batch 这么强,你会用吗?

    作者 | topEngineerray 来源 | blog.csdn.net/topdeveloperr/article/details/84337956 正文 spring batch简介 spri ...

  5. Spring Boot参考指南

    Spring Boot参考指南 作者 菲利普·韦伯,戴夫 Syer,约什 长,斯特凡 尼科尔,罗布 绞车,安迪·威尔金森,马塞尔 Overdijk,基督教 杜普伊斯,塞巴斯蒂安·德勒兹,迈克尔·西蒙斯 ...

  6. spring Batch实现数据库大数据量读写

    spring Batch实现数据库大数据量读写 博客分类: spring springBatchquartz定时调度批处理  1. data-source-context.xml Xml代码   &l ...

  7. Spring Batch在大型企业中的最佳实践

    在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...

  8. java中batch基础_详解Spring batch 入门学习教程(附源码)

    详解Spring batch 入门学习教程(附源码) 发布时间:2020-09-08 00:28:40 来源:脚本之家 阅读:99 作者:achuo Spring batch 是一个开源的批处理框架. ...

  9. 首次使用批处理框架 Spring Batch ,被震撼到了,太强大...

    以下文章来源方志朋的博客,回复"666"获面试宝典 spring batch简介 spring batch是spring提供的一个数据处理框架.企业域中的许多应用程序需要批量处理才 ...

最新文章

  1. android跳转应用市场搜索,Android 应用中跳转到应用市场评分
  2. CentOS7,使用tar命令解压缩文件
  3. MySQL常见面试题解析
  4. XSLT - 利用template实现for循环
  5. 4、常见命令操作(详细)
  6. 设置电子围栏 高德地图_地理围栏-辅助功能-开发指南-Android 定位SDK | 高德地图API...
  7. Linux抓eth0网卡包的命令,Linux系统使用tcpdump命令抓包
  8. arm poky linux,Solved: Re: arm-poky-linux - NXP Community
  9. 借用 FCKEditor 的文件上传/管理界面
  10. Tensorflow高级封装
  11. 多个 ng-app 中 Controllers Services 之间的通信
  12. HTML 编辑器简介
  13. “《三国演义》人物出场统计“实例讲解
  14. 雨天的尾巴——LCA+树上差分+动态开点+线段树合并
  15. 实现用户登录注册代码(高级代码)
  16. eclipse总是运行之前的代码,控制台只显示原先的结果
  17. 电商项目_ads层建设
  18. 如何让table边框变为单实线?
  19. Flash动画学习指南二:帧频(Frame rates)
  20. fastdfs+nginx+keepalived+openoffice+lua 实现文件上传、下载、水印、预览(word、excel、ppt、txt),feign文件上传

热门文章

  1. android百度输入法表情符号,分析Android 搜狗输入法在微信和QQ中发送图片和表情...
  2. 计算机网络基础常考简答题,计算机网络基础知识简答题
  3. docker 改host_所以到底该如何修改 docker 容器的端口映射!!!
  4. 解决CUDA driver version is insufficient for CUDA runtime version
  5. Python基础7(集合与深浅copy)
  6. Jzoj4743 积木
  7. FreeBSD 配置
  8. rubymongo_mapper
  9. 开启Python之路
  10. HDU 5514 Frogs (容斥原理)