一、SpringBatch介绍
Spring Batch 是一个轻量级、全面的批处理框架,旨在反对开发对企业零碎的日常操作至关重要的强壮的批处理应用程序。Spring Batch 建设在人们冀望的 Spring Framework 个性(生产力、基于 POJO 的开发方法和个别易用性)的根底上,同时使开发人员能够在必要时轻松拜访和应用更高级的企业服务。Spring Batch 不是一个调度框架。在商业和开源畛域都有许多优良的企业调度程序(例如 Quartz、Tivoli、Control-M 等)。Spring Batch 旨在与调度程序联合应用,而不是代替调度程序。
二、业务场景
咱们在业务开发中常常遇到这种状况:
Spring Batch 反对以下业务场景:
定期提交批处理。
并发批处理:并行处理作业。
分阶段的企业音讯驱动解决。
大规模并行批处理。
失败后手动或打算重启。
相干步骤的程序解决(扩大到工作流驱动的批次)。
局部解决:跳过记录(例如,在回滚时)。
整批交易,实用于批量较小或已有存储过程或脚本的状况。
三、基础知识
3.1、整体架构
官网文档:浏览地址
名称作用JobRepository为所有的原型(Job、JobInstance、Step)提供长久化的机制JobLauncherJobLauncher示意一个简略的接口,用于启动一个Job给定的汇合 JobParametersJobJob是封装了整个批处理过程的实体StepStep是一个域对象,它封装了批处理作业的一个独立的程序阶段
3.2、外围接口
ItemReader: is an abstraction that represents the output of a Step, one batch or chunk of items at a time
ItemProcessor:an abstraction that represents the business processing of an item.
ItemWriter: is an abstraction that represents the output of a Step, one batch or chunk of items at a time.
大体即为 输出→数据加工→输入 ,一个Job定义多个Step及解决流程,一个Step通常涵盖ItemReader、ItemProcessor、ItemWriter
四、根底实操
4.0、引入SpringBatch
pom文件引入springboot
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
复制代码
pom文件引入spring-batch及相干依赖
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency>
</dependencies>
复制代码
mysql创立依赖的库表
sql脚本的jar包门路: .....\maven\repository\org\springframework\batch\spring-batch-core\4.2.1.RELEASE\spring-batch-core-4.2.1.RELEASE.jar!\org\springframework\batch\core\schema-mysql.sql
启动类标记@EnableBatchProcessing
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchStartApplication
{
public static void main(String[] args) { SpringApplication.run(SpringBatchStartApplication.class, args); }
}
复制代码
FirstJobDemo
@Component
public class FirstJobDemo {
@Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job firstJob() { return jobBuilderFactory.get("firstJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .tasklet((contribution, chunkContext) -> { System.out.println("执行步骤...."); return RepeatStatus.FINISHED; }).build(); }
}