我是Spring和Spring Batch的新手 . 我写了一个基本的工作,应该每5秒重复一次 . 它有两个步骤,第一步( step1
)应该每次都失败 . 我的目的是查看作业是否会在 step1
中报告这些错误并继续 step2
. 我用来捕获 step1
中的错误的方法如下(使用 listener
s) . 我想对我的方法的正确与错误进行一些批评 .
这是我的工作配置 . 它有一个工作,有两个步骤:
@Configuration
public class JobConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobRepository jobRepository;
@Autowired
private StepExecutionListenerImpl stepExecutionListener;
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.listener(this.stepExecutionListener)
.tasklet(new Tasklet() throws Exception {
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
throw new Exception("Step1 caused an exception");
return RepeatStatus.FINISHED;
}
})
.build();
}
@Bean
public Step step2() {
return stepBuilderFactory.get("step2")
.tasklet(new Tasklet() {
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws InterruptedException {
System.out.println("Step2 is executing");
return RepeatStatus.FINISHED;
}
})
.build();
}
@Bean
public Job job() throws Exception {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(step1())
.on("COMPLETED").to(step2()).end()
.build();
}
@Scheduled(cron = "*/5 * * * * *")
public void runJob() throws Exception {
System.out.println("Job Started at :" + new Date());
JobParameters param = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
JobExecution execution = jobLauncher.run(job(), param);
System.out.println("Job finished with status :" + execution.getStatus());
}
@Bean
public JobLauncher getJobLauncher() {
SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
simpleJobLauncher.setJobRepository(this.jobRepository);
return simpleJobLauncher;
}
}
要在 step1
中导致错误,我在该步骤中抛出异常 . 我还在 step1
中添加了 listener
,其中 afterStep()
方法检查该步骤是否发生了异常,如果是,则返回 ExitStatus.FAILED
. 如果没有异常发生,则返回 ExitStatus.COMPLETED
. 以下是代码:
@Component
public class StepExecutionListenerImpl implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
System.out.println("Before starting step");
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
List<Throwable> exceptions = stepExecution.getFailureExceptions();
if(exceptions.isEmpty()) {
return ExitStatus.COMPLETED;
} else {
System.out.println("This step has encountered exceptions");
exceptions.forEach(th -> System.out.println("Exception has occurred in job"));
return ExitStatus.FAILED;
}
}
}
这似乎有效,因为 step1
在作业的每次迭代中失败,然后开始新的迭代 . 所以我的问题是,这是在Spring Batch作业中捕获错误的好方法吗?我正确使用听众吗?
1 回答
我们已经实现了
ItemReadListener
,ItemProcessListener
,ItemWriteListener
接口,其中包含onReadError
,onProcessError
,onWriteError
等方法 . 如果在读取/处理/写入记录的过程中发生任何异常,则调用这些方法 .