使用侦听器捕获Spring Batch

时间:2018-01-11 22:06:58

标签: java spring spring-batch

我是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中导致错误,我在该步骤中抛出异常。我还在listener中添加了step1,其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 个答案:

答案 0 :(得分:1)

我们已实施ItemReadListenerItemProcessListenerItemWriteListener个接口,其中包含onReadErroronProcessErroronWriteError等方法。如果在读取/处理/写入记录的过程中有任何异常,则调用这些方法。