Spring Batch
Job instance (作业实例)
当作业运行时,会创建一个Job Instance(作业实例),它代表作业的一次逻辑运行,可通过作业名称与作业标识参数进行区分。
比如一个业务需求: 每天定期数据同步,作业名称-daily-sync-job 作业标记参数-当天时间
Job Execution (作业执行对象)
当作业运行时,也会创建一个Job Execution(作业执行器),负责记录Job执行情况(比如:开始执行时间,结束时间,处理状态等)。
Job Instance = Job名称 + 识别参数
Job Instance 一次执行创建一个 Job Execution对象
完整的一次Job Instance 执行可能创建一个Job Execution对象,也可能创建多个Job Execution对象
入门案例-H2版
导入依赖
java
<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>
<!--内存版-->
<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>
测试方法
java
@Component
public class JobDemo1 {
//作业启动器
@Autowired
private JobLauncher jobLauncher;
//Job构造工厂(构建job对象)
@Autowired
private JobBuilderFactory jobBuilderFactory;
//step构造工厂(构建step对象)
@Autowired
private StepBuilderFactory stepBuilderFactory;
//构造一个step对象执行的任务
@Bean
public Tasklet tasklet(){
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
//要执行逻辑 step步骤执行逻辑
System.out.println("hello spring batch");
return RepeatStatus.FINISHED;
}
};
}
//构造一个step对象
@Bean
public Step step1(){
//tasklet指step执行逻辑
return stepBuilderFactory.get("step1").tasklet(tasklet()).build();
}
//构造job对象
//start(step1).next(step2)
@Bean
public Job job(){
return jobBuilderFactory.get("hello-job").start(step1()).build();
}
}
启动类
java
//启动springBatch
@EnableBatchProcessing
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
入门案例-MySQL版
依赖
java
<!-- <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency> -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.2</version>
</dependency>
application-dev.yaml
此处测试时并没有自动创建表
java
server:
port: 8896
spring:
datasource:
username: root
password: root
url: jdbc:mariadb://ip地址:3306/springbatch?serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true
driver-class-name: org.mariadb.jdbc.Driver
# 初始化数据库,文件在依赖jar包中
sql:
init:
schema-locations: classpath:org/springframework/batch/core/schema-mysql.sql
#mode: always
mode: never
其余代码与H2版本相同