如何防止Spring Batch Job在步骤失败时重新启动?

时间:2016-12-12 16:03:46

标签: spring spring-batch spring-cloud

我有简单的单步工作:

@Bean(name = "restProcessorJob")
public Job job(@Qualifier("step") Step step) throws Exception {
    return jobBuilderFactory.get("restProcessorJob")
            .start(step)
            .build();
}

如果在步骤执行期间出现异常,Batch框架将立即尝试再次执行它。

2016-12-12 18:49:45.558  INFO 10872 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=restProcessorJob]] launched with the following parameters: [{id=1481568585432}]
2016-12-12 18:49:45.572  INFO 10872 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step]
2016-12-12 18:49:45.597 DEBUG 10872 --- [           main] o.s.web.client.RestTemplate              : Created GET request for "http://myhost:myport.."
2016-12-12 18:49:45.646 DEBUG 10872 --- [           main] o.s.web.client.RestTemplate              : Setting request Accept header to [application/json, application/*+json]
2016-12-12 18:49:46.670 ERROR 10872 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step in job restProcessorJob

org.springframework.web.client.ResourceAccessException: I/O error on GET request Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
    ... 

2016-12-12 18:49:46.689  INFO 10872 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=restProcessorJob]] completed with the following parameters: [{id=1481568585432}] and the following status: [FAILED]
2016-12-12 18:49:46.690  INFO 10872 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2016-12-12 18:49:46.727  INFO 10872 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=restProcessorJob]] launched with the following parameters: [{id=1481568585432}]
2016-12-12 18:49:46.736  INFO 10872 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step]
...

有没有办法配置此类行为,并且在失败时不运行两次作业?

修改

似乎我找到了问题的根源。 Spring启动应用程序尝试启动它在上下文中找到的每个CommandLineRunner。在我的例子中,它是 org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner 。我一直试图排除这个类:

@EnableAutoConfiguration(excludeName="org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner")

但没有成功......

2 个答案:

答案 0 :(得分:1)

将.preventRestart与增量器一起使用

@Bean(name = "restProcessorJob")
public Job job(@Qualifier("step") Step step) throws Exception {
    return jobBuilderFactory.get("restProcessorJob")
            .start(step)
            .incrementer(new RunIdIncrementer())
            .preventRestart()
            .build();
}

答案 1 :(得分:0)

您可以在配置文件中配置它,您可以将跳过限制设置为0