- 一、SpringBatch 介绍
- 二、业务场景
- 三、基础知识
- 四、基础实操
一、SpringBatch 介绍
Spring Batch 是一个轻量级、全面的批处理框架,它的目标是支持开发健壮的批处理应用程序,这些应用程序对企业系统的日常操作至关重要。与其他框架相比,Spring Batch 是基于 Spring Framework 的特性、易用性和基于 POJO 的开发方法等优点而建立起来的。这使得开发人员能够轻松访问和使用更高级的企业服务,从而提高了应用程序的效率。
尽管 Spring Batch 不是一个调度框架,但是它可以与商业和开源领域的许多优秀的企业调度程序(例如 Quartz、Tivoli、Control-M 等)结合使用。与这些调度程序结合使用,Spring Batch 可以使得企业系统更加高效地运转,从而提高生产力和效益。
二、业务场景
我们在业务开发中经常遇到这种情况:
Spring Batch 支持以下业务场景:
- 定期提交批处理。
- 并发批处理:并行处理作业。
- 分阶段的企业消息驱动处理。
- 大规模并行批处理。
- 失败后手动或计划重启。
- 相关步骤的顺序处理(扩展到工作流驱动的批次)。
- 部分处理:跳过记录(例如,在回滚时)。
- 整批交易,适用于批量较小或已有存储过程或脚本的情况。
三、基础知识
3.1、整体架构
3.2、核心接口
ItemReader
: is an abstraction that represents the output of aStep
, one batch or chunk of items at a timeItemProcessor
:an abstraction that represents the business processing of an item.ItemWriter
: is an abstraction that represents the output of aStep
, one batch or chunk of items at a time.
大体即为 输入
→数据加工
→输出
,一个Job
定义多个Step
及处理流程,一个Step
通常涵盖ItemReader
、ItemProcessor
、ItemWriter
四、基础实操
4.0、引入 SpringBatch
pom 文件引入 springboot
pom 文件引入 spring-batch 及相关依赖
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
FirstJobDemo
4.1、流程控制
A、多步骤任务
B、并行执行
创建了两个 Flow:flow1(包含 step1 和 step2)和 flow2(包含 step3)。然后通过JobBuilderFactory
的split
方法,指定一个异步执行器,将 flow1 和 flow2 异步执行(也就是并行)
C、任务决策
决策器的作用就是可以指定程序在不同的情况下运行不同的任务流程,比如今天是周末,则让任务执行 step1 和 step2,如果是工作日,则之心 step1 和 step3。
D、任务嵌套
任务 Job 除了可以由 Step 或者 Flow 构成外,我们还可以将多个任务 Job 转换为特殊的 Step,然后再赋给另一个任务 Job,这就是任务的嵌套。
4.2、读取数据
定义 Model TestData
,下面同一
读取数据包含:文本数据读取、数据库数据读取、XML 数据读取、JSON 数据读取等,具体自己查资料。
文本数据读取 Demo
4.3、输出数据
输出数据也包含:文本数据读取、数据库数据读取、XML 数据读取、JSON 数据读取等
4.5、处理数据
4.6、任务调度
可以配合 quartz 或者 xxljob 实现定时任务执行