SpringBatch簡單入門案例
一、學(xué)習(xí)目標(biāo)
學(xué)習(xí)目標(biāo)
- 系統(tǒng)了解Spring Batch批處理
- 項目中能熟練使用Spring Batch批處理
前置知識
- Java基礎(chǔ)
- Maven
- Spring SpringMVC SpringBoot
- MyBatis
二、Spring Batch簡介
2.1 何為批處理?
何為批處理,大白話:就是將數(shù)據(jù)分批次進行處理的過程。比如:銀行對賬邏輯,跨系統(tǒng)數(shù)據(jù)同步等。
常規(guī)的批處理操作步驟:系統(tǒng)A從數(shù)據(jù)庫中導(dǎo)出數(shù)據(jù)到文件,系統(tǒng)B讀取文件數(shù)據(jù)并寫入到數(shù)據(jù)庫

典型批處理特點:
- 自動執(zhí)行,根據(jù)系統(tǒng)設(shè)定的工作步驟自動完成
- 數(shù)據(jù)量大,少則百萬,多則上千萬甚至上億。(如果是10億,100億那只能上大數(shù)據(jù)了)
- 定時執(zhí)行,比如:每天,每周,每月執(zhí)行。
2.2 Spring Batch了解
官網(wǎng)介紹:https://docs.spring.io/spring-batch/docs/current/reference/html/spring-batch-intro.html#spring-batch-intro
這里挑重點講下:
- Sping Batch 是一個輕量級的、完善的的批處理框架,旨在幫助企業(yè)建立健壯、高效的批處理應(yīng)用。
- Spring Batch 是Spring的一個子項目,基于Spring框架為基礎(chǔ)的開發(fā)的框架
- Spring Batch 提供大量可重用的組件,比如:日志,追蹤,事務(wù),任務(wù)作業(yè)統(tǒng)計,任務(wù)重啟,跳過,重復(fù),資源管理等
- Spring Batch 是一個批處理應(yīng)用框架,不提供調(diào)度框架,如果需要定時處理需要額外引入-調(diào)度框架,比如: Quartz
2.3 Spring Batch 優(yōu)勢
Spring Batch 框架通過提供豐富的開箱即用的組件和高可靠性、高擴展性的能力,使得開發(fā)批處理應(yīng)用的人員專注于業(yè)務(wù)處理,提高處理應(yīng)用的開發(fā)能力。下面就是使用Spring Batch后能獲取到優(yōu)勢:
- 豐富的開箱即用組件
- 面向Chunk的處理
- 事務(wù)管理能力
- 元數(shù)據(jù)管理
- 易監(jiān)控的批處理應(yīng)用
- 豐富的流程定義
- 健壯的批處理應(yīng)用
- 易擴展的批處理應(yīng)用
- 復(fù)用企業(yè)現(xiàn)有的IT代碼
2.4 Spring Batch 架構(gòu)
Spring Batch 核心架構(gòu)分三層:應(yīng)用層,核心層,基礎(chǔ)架構(gòu)層。

Application:應(yīng)用層,包含所有的批處理作業(yè),程序員自定義代碼實現(xiàn)邏輯。
Batch Core:核心層,包含Spring Batch啟動和控制所需要的核心類,比如:JobLauncher, Job,Step等。
Batch Infrastructure:基礎(chǔ)架構(gòu)層,提供通用的讀,寫與服務(wù)處理。
三層體系使得Spring Batch 架構(gòu)可以在不同層面進行擴展,避免影響,實現(xiàn)高內(nèi)聚低耦合設(shè)計。
三、入門案例
3.1 批量處理流程
前面對Spring Batch 有大體了解之后,那么開始寫個案例玩一下。
開始前,先了解一下Spring Batch程序運行大綱:
**

JobLauncher:作業(yè)調(diào)度器,作業(yè)啟動主要入口。
Job:作業(yè),需要執(zhí)行的任務(wù)邏輯,
Step:作業(yè)步驟,一個Job作業(yè)由1個或者多個Step組成,完成所有Step操作,一個完整Job才算執(zhí)行結(jié)束。
ItemReader:Step步驟執(zhí)行過程中數(shù)據(jù)輸入。可以從數(shù)據(jù)源(文件系統(tǒng),數(shù)據(jù)庫,隊列等)中讀取Item(數(shù)據(jù)記錄)。
ItemWriter:Step步驟執(zhí)行過程中數(shù)據(jù)輸出,將Item(數(shù)據(jù)記錄)寫入數(shù)據(jù)源(文件系統(tǒng),數(shù)據(jù)庫,隊列等)。
ItemProcessor:Item數(shù)據(jù)加工邏輯(輸入),比如:數(shù)據(jù)清洗,數(shù)據(jù)轉(zhuǎn)換,數(shù)據(jù)過濾,數(shù)據(jù)校驗等
JobRepository: 保存Job或者檢索Job的信息。SpringBatch需要持久化Job(可以選擇數(shù)據(jù)庫/內(nèi)存),JobRepository就是持久化的接口
3.2 入門案例-H2版(內(nèi)存)

需求:打印一個hello spring batch!不帶讀/寫/處理
步驟1:導(dǎo)入依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--內(nèi)存版-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>其中的h2是一個嵌入式內(nèi)存數(shù)據(jù)庫,后續(xù)可以使用MySQL替換
步驟2:創(chuàng)建測試方法
package com.langfeiyes.batch._01_hello;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableBatchProcessing
public class HelloJob {
//job調(diào)度器
@Autowired
private JobLauncher jobLauncher;
//job構(gòu)造器工廠
@Autowired
private JobBuilderFactory jobBuilderFactory;
//step構(gòu)造器工廠
@Autowired
private StepBuilderFactory stepBuilderFactory;
//任務(wù)-step執(zhí)行邏輯由tasklet完成
@Bean
public Tasklet tasklet(){
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("Hello SpringBatch....");
return RepeatStatus.FINISHED;
}
};
}
//作業(yè)步驟-不帶讀/寫/處理
@Bean
public Step step1(){
return stepBuilderFactory.get("step1")
.tasklet(tasklet())
.build();
}
//定義作業(yè)
@Bean
public Job job(){
return jobBuilderFactory.get("hello-job")
.start(step1())
.build();
}
public static void main(String[] args) {
SpringApplication.run(HelloJob.class, args);
}
}步驟3:分析
例子是一個簡單的SpringBatch 入門案例,使用了最簡單的一種步驟處理模型:Tasklet模型,step1中沒有帶上讀/寫/處理邏輯,只有簡單打印操作,后續(xù)隨學(xué)習(xí)深入,我們再講解更復(fù)雜化模型。
package com.zyy.batch._01hello;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* Spring Batch 入門示例
*
* Spring Batch 核心組件:
* - JobLauncher: 作業(yè)調(diào)度器,作業(yè)啟動的主要入口
* - Job: 作業(yè),需要執(zhí)行的任務(wù)邏輯
* - Step: 作業(yè)步驟,一個Job由1個或多個Step組成,完成所有Step后,Job才算執(zhí)行結(jié)束
* - ItemReader: 數(shù)據(jù)讀取器,從數(shù)據(jù)源(文件系統(tǒng),數(shù)據(jù)庫,隊列等)中讀取數(shù)據(jù)記錄
* - ItemWriter: 數(shù)據(jù)寫入器,將數(shù)據(jù)記錄寫入目標(biāo)數(shù)據(jù)源
* - ItemProcessor: 數(shù)據(jù)處理器,進行數(shù)據(jù)清洗、轉(zhuǎn)換、過濾、校驗等操作
* - JobRepository: 作業(yè)倉庫,保存和檢索Job信息,實現(xiàn)Job的持久化(數(shù)據(jù)庫或內(nèi)存)
*/
@EnableBatchProcessing // 開啟Spring Batch功能,讓Spring容器創(chuàng)建相關(guān)組件
@SpringBootApplication // 標(biāo)記為SpringBoot應(yīng)用啟動類
public class HelloJob {
// 自動注入Spring Batch核心組件
@Autowired
private JobLauncher jobLauncher; // 作業(yè)啟動器
@Autowired
private JobBuilderFactory jobBuilderFactory; // Job構(gòu)建工廠
@Autowired
private StepBuilderFactory stepBuilderFactory; // Step構(gòu)建工廠
/**
* 創(chuàng)建Tasklet,定義Step的執(zhí)行邏輯
* Tasklet是最簡單的Step實現(xiàn)方式,適合簡單的處理邏輯
*/
@Bean
public Tasklet tasklet() {
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// 業(yè)務(wù)邏輯實現(xiàn)
System.out.println("hello 瓦塔西在學(xué)習(xí)springbatch");
// 返回執(zhí)行狀態(tài):FINISHED表示執(zhí)行完成
return RepeatStatus.FINISHED;
}
};
}
/**
* 創(chuàng)建Step,一個Job可以包含多個Step
*/
@Bean
public Step step1() {
// 使用構(gòu)建器模式創(chuàng)建Step
return stepBuilderFactory.get("step1") // 指定Step名稱
.tasklet(tasklet()) // 綁定Tasklet
.build(); // 構(gòu)建Step對象
}
/**
* 創(chuàng)建Job,整個批處理作業(yè)的入口
*/
@Bean
public Job job() {
// 使用構(gòu)建器模式創(chuàng)建Job
return jobBuilderFactory.get("hello-job") // 指定Job名稱
.start(step1()) // 指定起始Step
.build(); // 構(gòu)建Job對象
}
/**
* 應(yīng)用程序入口
*/
public static void main(String[] args) {
SpringApplication.run(HelloJob.class, args);
}
}詳細(xì)到逆天的分析
package com.zyy.batch._01hello;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* Spring Batch 入門示例 - Hello World Job
*
* Spring Batch 是一個批處理框架,用于處理大量數(shù)據(jù)操作。它提供了可重用的功能,如日志/跟蹤,
* 事務(wù)管理,作業(yè)處理統(tǒng)計,作業(yè)重啟,跳過和資源管理等。
*
* 核心概念詳解:
*
* 1. JobLauncher - 作業(yè)調(diào)度器
* - 負(fù)責(zé)啟動Job的執(zhí)行
* - 可以同步或異步方式運行Job
* - 處理Job參數(shù)的傳遞
*
* 2. Job - 批處理作業(yè)
* - 表示一個完整的批處理過程
* - 由一個或多個Step組成
* - 具有自己的生命周期和狀態(tài)管理
*
* 3. Step - 作業(yè)步驟
* - Job的組成部分,表示Job中的一個獨立工作階段
* - 可以是簡單的Tasklet模式,也可以是復(fù)雜的Chunk處理模式
* - 每個Step可以有自己的ItemReader, ItemProcessor和ItemWriter
*
* 4. Tasklet - 任務(wù)組件
* - 最簡單的Step實現(xiàn)方式
* - 用于簡單的處理邏輯,例如執(zhí)行存儲過程、文件操作等
* - 一次性執(zhí)行的任務(wù)單元
*
* 5. ItemReader - 數(shù)據(jù)讀取器
* - 負(fù)責(zé)從各種數(shù)據(jù)源(文件、數(shù)據(jù)庫、消息隊列等)讀取數(shù)據(jù)
* - 一次讀取一條數(shù)據(jù)記錄
* - 支持多種數(shù)據(jù)源的讀取策略
*
* 6. ItemProcessor - 數(shù)據(jù)處理器
* - 對ItemReader讀取的數(shù)據(jù)進行處理
* - 可進行數(shù)據(jù)轉(zhuǎn)換、驗證、過濾、清洗等操作
* - 是可選組件,可以沒有
*
* 7. ItemWriter - 數(shù)據(jù)寫入器
* - 負(fù)責(zé)將處理后的數(shù)據(jù)寫入目標(biāo)位置
* - 批量寫入多條數(shù)據(jù)記錄
* - 支持多種目標(biāo)位置(文件、數(shù)據(jù)庫、消息隊列等)
*
* 8. JobRepository - 作業(yè)倉庫
* - 持久化和檢索Job相關(guān)的元數(shù)據(jù)
* - 跟蹤Job的執(zhí)行狀態(tài)
* - 存儲Job的執(zhí)行歷史信息
*
* 9. JobInstance - 作業(yè)實例
* - 特定Job的邏輯運行單元
* - 由Job和JobParameters組合確定
* - 每次使用相同參數(shù)運行同一Job時會重用JobInstance
*
* 10. JobExecution - 作業(yè)執(zhí)行
* - 表示一次Job運行的嘗試
* - 包含運行狀態(tài)、開始時間、結(jié)束時間等信息
* - 一個JobInstance可以有多個JobExecution(如失敗后重試)
*
* 11. StepExecution - 步驟執(zhí)行
* - 表示一次Step運行的嘗試
* - 記錄Step執(zhí)行的詳細(xì)信息
* - 包含讀取、處理、寫入和跳過的記錄數(shù)等統(tǒng)計信息
*
* 12. ExecutionContext - 執(zhí)行上下文
* - 保存執(zhí)行過程中的狀態(tài)信息
* - 用于作業(yè)重啟時恢復(fù)狀態(tài)
* - 存在于JobExecution和StepExecution級別
*/
@EnableBatchProcessing // 啟用Spring Batch功能,自動配置JobRepository, JobLauncher, JobRegistry等組件
@SpringBootApplication // 標(biāo)識為SpringBoot應(yīng)用的啟動類,啟用自動配置和組件掃描
public class HelloJob {
/**
* JobLauncher - 作業(yè)啟動器
*
* 職責(zé):
* 1. 接收并驗證Job和JobParameters
* 2. 根據(jù)Job和JobParameters解析對應(yīng)的JobInstance
* 3. 創(chuàng)建JobExecution并執(zhí)行Job
* 4. 處理作業(yè)執(zhí)行中的異常
* 5. 返回JobExecution給調(diào)用者
*
* 注:通過@EnableBatchProcessing注解,Spring Boot會自動創(chuàng)建并注冊JobLauncher Bean
*/
@Autowired // 自動注入由Spring容器管理的JobLauncher實例
private JobLauncher jobLauncher;
/**
* JobBuilderFactory - Job構(gòu)建工廠
*
* 作用:
* 1. 提供流式API創(chuàng)建和配置Job
* 2. 簡化Job的創(chuàng)建過程
* 3. 設(shè)置Job的各種屬性(名稱、監(jiān)聽器、驗證器等)
* 4. 配置Job的流程控制(順序執(zhí)行、條件執(zhí)行等)
*
* 常用方法:
* - get(String name): 創(chuàng)建指定名稱的JobBuilder
* - start(Step step): 設(shè)置Job的第一個Step
* - next(Step step): 添加下一個要執(zhí)行的Step
* - flow(Step step): 創(chuàng)建基于流程的Job
* - validator(JobParametersValidator validator): 設(shè)置參數(shù)驗證器
* - listener(JobExecutionListener listener): 添加Job執(zhí)行監(jiān)聽器
*/
@Autowired // 自動注入由Spring容器管理的JobBuilderFactory實例
private JobBuilderFactory jobBuilderFactory;
/**
* StepBuilderFactory - Step構(gòu)建工廠
*
* 作用:
* 1. 提供流式API創(chuàng)建和配置Step
* 2. 簡化Step的創(chuàng)建過程
* 3. 支持創(chuàng)建不同類型的Step(Tasklet步驟、Chunk步驟)
* 4. 配置Step的各種屬性(名稱、監(jiān)聽器、事務(wù)等)
*
* 常用方法:
* - get(String name): 創(chuàng)建指定名稱的StepBuilder
* - tasklet(Tasklet tasklet): 創(chuàng)建Tasklet類型的Step
* - chunk(int commitInterval): 創(chuàng)建Chunk類型的Step,指定提交間隔
* - reader(ItemReader reader): 設(shè)置數(shù)據(jù)讀取器
* - processor(ItemProcessor processor): 設(shè)置數(shù)據(jù)處理器
* - writer(ItemWriter writer): 設(shè)置數(shù)據(jù)寫入器
* - listener(StepExecutionListener listener): 添加Step執(zhí)行監(jiān)聽器
* - faultTolerant(): 配置容錯處理
* - transactionManager(PlatformTransactionManager tm): 設(shè)置事務(wù)管理器
*/
@Autowired // 自動注入由Spring容器管理的StepBuilderFactory實例
private StepBuilderFactory stepBuilderFactory;
/**
* 創(chuàng)建Tasklet - 定義Step的執(zhí)行邏輯
*
* Tasklet是Step的最簡單實現(xiàn)方式,適合簡單的處理邏輯。
* 它的execute方法會被反復(fù)調(diào)用,直到返回RepeatStatus.FINISHED或拋出異常。
*
* 參數(shù)說明:
* - StepContribution: 包含更新當(dāng)前StepExecution所需的信息
* - ChunkContext: 包含當(dāng)前Step執(zhí)行的相關(guān)上下文信息
*
* 返回值說明:
* - RepeatStatus.FINISHED: 表示Tasklet執(zhí)行完成,不再重復(fù)執(zhí)行
* - RepeatStatus.CONTINUABLE: 表示Tasklet需要繼續(xù)執(zhí)行
*
* @return 配置好的Tasklet實例
*/
@Bean // 標(biāo)記為Spring Bean,由Spring容器管理生命周期
public Tasklet tasklet() {
// 創(chuàng)建匿名內(nèi)部類實現(xiàn)Tasklet接口
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// 實現(xiàn)業(yè)務(wù)邏輯 - 這里只是簡單打印一條消息
System.out.println("hello 瓦塔西在學(xué)習(xí)springbatch");
// 返回FINISHED狀態(tài),表示任務(wù)執(zhí)行完成,不再重復(fù)執(zhí)行
return RepeatStatus.FINISHED;
// 注:如果返回RepeatStatus.CONTINUABLE,則會重復(fù)執(zhí)行此Tasklet
}
};
// 也可以使用Lambda表達式簡化代碼:
// return (contribution, chunkContext) -> {
// System.out.println("hello 瓦塔西在學(xué)習(xí)springbatch");
// return RepeatStatus.FINISHED;
// };
}
/**
* 創(chuàng)建Step - 定義批處理作業(yè)的一個步驟
*
* Step表示批處理作業(yè)中的一個獨立階段,可以配置自己的處理邏輯、事務(wù)控制、重啟策略等。
* 這里使用最簡單的Tasklet類型Step,適合一次性執(zhí)行的簡單任務(wù)。
*
* 構(gòu)建過程:
* 1. 使用stepBuilderFactory.get()獲取StepBuilder
* 2. 通過StepBuilder配置Step屬性
* 3. 調(diào)用build()方法創(chuàng)建Step實例
*
* @return 配置好的Step實例
*/
@Bean // 標(biāo)記為Spring Bean,由Spring容器管理生命周期
public Step step1() {
return stepBuilderFactory
.get("step1") // 指定Step名稱,用于在Job執(zhí)行過程中標(biāo)識該Step
.tasklet(tasklet()) // 使用上面定義的Tasklet實現(xiàn)Step的處理邏輯
.build(); // 構(gòu)建Step對象并返回
// 更復(fù)雜的Step配置示例(僅供參考):
// return stepBuilderFactory.get("step1")
// .tasklet(tasklet())
// .listener(new StepExecutionListener() { ... }) // 添加Step執(zhí)行監(jiān)聽器
// .allowStartIfComplete(true) // 允許重新執(zhí)行已完成的Step
// .startLimit(3) // 設(shè)置重啟次數(shù)上限
// .build();
}
/**
* 創(chuàng)建Job - 定義整個批處理作業(yè)
*
* Job是Spring Batch中的頂級概念,表示一個完整的批處理過程。
* 它由一個或多個Step組成,定義了Steps的執(zhí)行順序和條件。
*
* 構(gòu)建過程:
* 1. 使用jobBuilderFactory.get()獲取JobBuilder
* 2. 通過JobBuilder配置Job屬性和流程
* 3. 調(diào)用build()方法創(chuàng)建Job實例
*
* @return 配置好的Job實例
*/
@Bean // 標(biāo)記為Spring Bean,由Spring容器管理生命周期
public Job job() {
return jobBuilderFactory
.get("hello-job") // 指定Job名稱,用于在執(zhí)行和監(jiān)控中標(biāo)識該Job
.start(step1()) // 設(shè)置Job的第一個Step
.build(); // 構(gòu)建Job對象并返回
// 多步驟Job配置示例(僅供參考):
// return jobBuilderFactory.get("hello-job")
// .start(step1())
// .next(step2())
// .next(step3())
// .listener(new JobExecutionListener() { ... }) // 添加Job執(zhí)行監(jiān)聽器
// .validator(new JobParametersValidator() { ... }) // 添加參數(shù)驗證器
// .preventRestart() // 禁止重啟該Job
// .build();
// 條件分支Job配置示例(僅供參考):
// return jobBuilderFactory.get("hello-job")
// .start(step1())
// .on("COMPLETED").to(step2()) // 如果step1完成,則執(zhí)行step2
// .from(step1()).on("FAILED").to(errorStep()) // 如果step1失敗,則執(zhí)行errorStep
// .end()
// .build();
}
/**
* 應(yīng)用程序入口方法
*
* 作用:
* 1. 啟動SpringBoot應(yīng)用
* 2. 初始化Spring上下文
* 3. 注冊和配置所有Bean
* 4. 觸發(fā)批處理作業(yè)的執(zhí)行
*
* 注:
* 在默認(rèn)配置下,當(dāng)應(yīng)用啟動時,Spring Batch會自動執(zhí)行所有已配置的Job。
* 這一行為可通過application.properties中的spring.batch.job.enabled=false禁用。
*
* @param args 命令行參數(shù)
*/
public static void main(String[] args) {
// 啟動SpringBoot應(yīng)用,傳入主類和命令行參數(shù)
SpringApplication.run(HelloJob.class, args);
// 注:如果需要手動控制Job的啟動,可以注入JobLauncher和Job,然后使用以下代碼啟動Job:
// JobParameters parameters = new JobParametersBuilder()
// .addLong("time", System.currentTimeMillis())
// .toJobParameters();
// jobLauncher.run(job, parameters);
}
}3.3 入門案例-MySQL版
MySQL跟上面的h2一樣,區(qū)別在連接數(shù)據(jù)庫不一致。
步驟1:在H2版本基礎(chǔ)上導(dǎo)入MySQL依賴
爆紅記得多刷新maven
<!-- <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency> -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>步驟2:配置數(shù)據(jù)庫四要素與初始化SQL腳本
spring:
datasource:
# 數(shù)據(jù)庫四要素 賬號 密碼 鏈接地址 驅(qū)動名稱
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/springbatch?serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
# 初始化數(shù)據(jù)庫,文件在依賴jar包中
sql:
init:
schema-locations: classpath:org/springframework/batch/core/schema-mysql.sql
# mode: always
mode: never
# 全局搜索快捷鍵 ctrl n 或者 Shift按兩次
# 繁體簡體轉(zhuǎn)換 “Ctrl + Shift + F” 快捷鍵這里要注意, sql.init.model 第一次啟動為always, 后面啟動需要改為never,否則每次執(zhí)行SQL都會異常。
第一次啟動會自動執(zhí)行指定的腳本,后續(xù)不需要再初始化

步驟3:測試
跟H2版一樣。
如果是想再執(zhí)行,需要換一下job名字,不然springboot不會執(zhí)行:Hello-job1
四、入門案例解析
idea 查看 類 所有方法的快捷鍵
Idea:ctrl+F12
Eclipse:Ctrl+O
1>@EnableBatchProcessing
批處理啟動注解,要求貼配置類或者啟動類上
@SpringBootApplication
@EnableBatchProcessing
public class HelloJob {
...
}
貼上@EnableBatchProcessing注解后,SpringBoot會自動加載JobLauncher JobBuilderFactory StepBuilderFactory 類并創(chuàng)建對象交給容器管理,要使用時,直接@Autowired即可
//job調(diào)度器 @Autowired private JobLauncher jobLauncher; //job構(gòu)造器工廠 @Autowired private JobBuilderFactory jobBuilderFactory; //step構(gòu)造器工廠 @Autowired private StepBuilderFactory stepBuilderFactory;
2>配置數(shù)據(jù)庫四要素
批處理允許重復(fù)執(zhí)行,異常重試,此時需要保存批處理狀態(tài)與數(shù)據(jù),Spring Batch 將數(shù)據(jù)緩存在H2內(nèi)存中或者緩存在指定數(shù)據(jù)庫中。入門案例如果要保存在MySQL中,所以需要配置數(shù)據(jù)庫四要素。
3>創(chuàng)建Tasklet對象
//任務(wù)-step執(zhí)行邏輯由tasklet完成
@Bean
public Tasklet tasklet(){
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("Hello SpringBatch....");
return RepeatStatus.FINISHED;
}
};
}
Tasklet負(fù)責(zé)批處理step步驟中具體業(yè)務(wù)執(zhí)行,它是一個接口,有且只有一個execute方法,用于定制step執(zhí)行邏輯。
public interface Tasklet {
RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception;
}
execute方法返回值是一個狀態(tài)枚舉類:RepeatStatus,里面有可繼續(xù)執(zhí)行態(tài)與已經(jīng)完成態(tài)
public enum RepeatStatus {
/**
* 可繼續(xù)執(zhí)行的-tasklet返回這個狀態(tài)會進入死循環(huán)
*/
CONTINUABLE(true),
/**
* 已經(jīng)完成態(tài)
*/
FINISHED(false);
....
}
4>創(chuàng)建Step對象
//作業(yè)步驟-不帶讀/寫/處理
@Bean
public Step step1(){
return stepBuilderFactory.get("step1")
.tasklet(tasklet())
.build();
}
Job作業(yè)執(zhí)行靠Step步驟執(zhí)行,入門案例選用最簡單的Tasklet模式,后續(xù)再講Chunk塊處理模式。
5>創(chuàng)建Job并執(zhí)行Job
//定義作業(yè)
@Bean
public Job job(){
return jobBuilderFactory.get("hello-job")
.start(step1())
.build();
}
創(chuàng)建Job對象交給容器管理,當(dāng)springboot啟動之后,會自動去從容器中加載Job對象,并將Job對象交給JobLauncherApplicationRunner類,再借助JobLauncher類實現(xiàn)job執(zhí)行。
驗證過程;



到此這篇關(guān)于SpringBatch簡單入門案例的文章就介紹到這了,更多相關(guān)SpringBatch入門內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring boot中多線程開發(fā)的注意事項總結(jié)
spring boot 通過任務(wù)執(zhí)行器 taskexecutor 來實現(xiàn)多線程和并發(fā)編程。下面這篇文章主要給大家介紹了關(guān)于spring boot中多線程開發(fā)的注意事項,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09
淺談MultipartFile中transferTo方法的坑
這篇文章主要介紹了MultipartFile中transferTo方法的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Springboot+Mybatis+logback打印sql腳本日志實現(xiàn)過程
在SpringBoot項目中,通過配置`application.yml`和`logback-spring.xml`文件,可以在控制臺和日志文件中打印SQL腳本日志,關(guān)鍵在于配置logback-spring.xml中的`name`屬性為mapper類所在路徑2026-01-01

