重试不适用于Java Config的Spring Batch

时间:2019-05-16 13:51:26

标签: java spring-boot spring-batch spring-retry

我的Spring批处理作业具有以下配置:

@Bean
public Job myJob(Step step1, Step step2, Step step3) {
    return jobs.get("myJob").start(step1).next(step2).next(step3).build();
}

@Bean
public Step step1(ItemReader<String> myReader,
                ItemProcessor<String, String> myProcessor,
                ItemWriter<String> myWriter) {
    return steps.get("step1").<String, String>chunk(1)
            .reader(myReader)
            .faultTolerant().retryLimit(3).retry(MyException.class)
            .processor(myProcessor)
            .writer(myWriter)
            .build();
}

@Bean
@StepScope
public MyReader myReader() {
    return new MyReader();
}
@Bean
public MyProcessor myProcessor() {
    return new MyProcessor();
}
@Bean
public MyWriter myWriter() {
    return new MyWriter();
}

当MyReader类抛出MyException时,它将停止执行作业,而不会重试以下堆栈跟踪:

2019-05-16 14:45:09.460 ERROR 22485 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step step1 in job myJob

org.springframework.batch.core.step.skip.NonSkippableReadException: Non-skippable exception during read
    at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:105) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
    at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:116) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]

2 个答案:

答案 0 :(得分:1)

  

当MyReader类抛出MyException时,它将在不重试的情况下停止执行作业

重试策略不适用于商品阅读器。因此,即使您将异常声明为可重试并且从读取器抛出该异常,重试策略也不会被调用。

重试策略仅适用于处理器和写入器。

答案 1 :(得分:0)

似乎从2.2.0开始,重试功能已从Spring Batch中撤出。现在,它是新库Spring Retry的一部分。 https://docs-stage.spring.io/spring-batch/docs/current/reference/html/retry.html#retry

通过声明性重试来处理此问题的步骤:

步骤1: 在应用程序中包含@EnableRetry

Spet 2: 根据{{​​3}}

添加aop入门

成绩         运行时('org.springframework.boot:spring-boot-starter-aop')

Maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <scope>runtime</scope>
</dependency>

Spet 3:@Retryable

中包含MyReader
@Override
@Retryable(include = { MyException.class }, maxAttempts = 5)
public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {

示例代码已签入github:https://github.com/spring-projects/spring-retry#additional-dependencies

示例输出:

MyReader : 0
MyProcessor : 0
MyWriter : [0]
MyReader : 1
MyProcessor : 1
MyWriter : [1]
MyReader : 2
MyProcessor : 2
MyWriter : [2]
MyReader : 3
****
MyReader : 3
****
MyReader : 3
****
MyReader : 3
MyProcessor : 3
MyWriter : [3]
MyReader : 4
MyProcessor : 4
MyWriter : [4]
MyReader : 5