Spring批处理Java配置:异常时跳过步骤并转到下一步

Spring Batch Java Config: Skip step when exception and go to next steps

例如我在工作中有 3 个步骤(类似于步骤 1):

@Autowired
private StepBuilderFactory stepBuilderFactory;

@Bean
public Step step1() {
    return stepBuilderFactory
            .get("step1")
            .<String, String> chunk(1)
            .reader(reader())
            .processor(processor())
            .writer(writer())
            .build();
}

如何在步骤 1 出现异常后继续执行步骤 2 和步骤 3?我的意思是 Java.

中的配置

您可以使用 StepBuilder.faultTolerant 方法并以这种方式配置 xml。

<batch:skippable-exception-classes>
                    <batch:include class="MyException"/>
</batch:skippable-exception-classes>

这对你的情况会有帮助。

请看这个:http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/core/step/builder/SimpleStepBuilder.html#faultTolerant--

您可以使用Skip Listener

@Component
public class CustomSkipListener {

    @OnSkipInRead
    public void onSkipInRead(Throwable t) {
        System.out.println("From onSkipInRead -> " + t.getMessage());
    }

    @OnSkipInWrite
    public void onSkipInWrite(String item, Throwable t) {
        System.out.println("From onSkipInWrite: " + item + " -> " + t.getMessage());
    }

    @OnSkipInProcess
    public void onSkipInProcess(String item, Throwable t) {
        System.out.println("From onSkipInProcess: " + string + " -> " + t.getMessage());
    }
}

然后在你的步骤

@Bean
public Step step1(CustomSkipListener customSkipListener) {
    return stepBuilderFactory
            .get("step1")
            .<String, String> chunk(1)
            .reader(reader())
            .processor(processor())
            .writer(writer())
            .faultTolerant()
            .skipLimit(10)
            .skip(RuntimeException.class)
            .listener(customSkipListener)
            .build();
}

Notice the CHAIN starting from .faultTolerant(). Adding the listener is not mandatory. If you add the listener you can handle the behaviour when skipping happens.

一些有用的链接

http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/core/SkipListener.html

http://docs.spring.io/spring-batch/reference/html/configureStep.html#configuringSkip

这里是一个关于如何在创建流时配置它的例子。这应该类似于直接使用作业生成器配置它:

return new FlowBuilder<SimpleFlow>("name")
    .start(step1) //
    .next(step2).on(ExitStatus.FAILED.getExitCode()).to(errorStep)
    .from(step2).on(ALL_PATTERN).to(step3)
    .build();