Job 的创建和使用
Flow的创建
顺序的执行step1 >> step2 >> step3
package com.it2.springbootspringbatch01.config;
import lombok.extern.slf4j.Slf4j;
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.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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableBatchProcessing
@Slf4j
public class JobDemo {
//注入任务对象工厂
@Autowired
private JobBuilderFactory jobBuilderFactory;
//任务的执行由Step决定,注入step对象的factory
@Autowired
private StepBuilderFactory stepBuilderFactory;
//创建Job对象
@Bean
public Job jobDemo1() {
return jobBuilderFactory.get("jobDemo1")
.start(step1()).next(step2()).next(step3())
.build();
}
//创建Step对象
@Bean
public Step step1() {
return stepBuilderFactory.get("step1").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
log.info("------step1 ok");
return RepeatStatus.FINISHED;
}
}).build();
}
//创建Step对象
@Bean
public Step step2() {
return stepBuilderFactory.get("step2").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
log.info("------step2 ok");
return RepeatStatus.FINISHED;
}
}).build();
}
//创建Step对象
@Bean
public Step step3() {
return stepBuilderFactory.get("step3").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
log.info("------step3 ok");
return RepeatStatus.FINISHED;
}
}).build();
}
}
我们也可以修改其流程,当其什么状态,from从哪个step到哪个step
//创建Job对象
@Bean
public Job jobDemo1() {
// return jobBuilderFactory.get("jobDemo1")
// .start(step1()).next(step2()).next(step3())
// .build();
return jobBuilderFactory.get("jobDemo1")
.start(step1())
.on("COMPLETED").to(step2())
.from(step2()).on("COMPLETED").to(step3()).end()
.build();
}
Flow是一组Step的集合,一个Job可以包含多个Flow,一个Flow可以包含多个Step,同时一个Job也可以同时包含Flow和Step。
如下代码,我们定义了一个flow1 ,而job1里面包含了flow1 ,同时next去到step3。
/**
* 创建Flow对象,声明flow中包含哪些step
* @return
*/
@Bean
public Flow flow1(){
return new FlowBuilder<Flow>("flow1").start(step1()).next(step2()).build();
}
@Bean
public Job job1(){
return jobBuilderFactory.get("job1").start(flow1()).next(step3()).end().build();
}