Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

e.g. i have 3 Steps in Job (similar to Step1):

@Autowired
private StepBuilderFactory stepBuilderFactory;

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

How go to Step 2 and 3 even after exception in Step 1? I mean configuration in Java.

like image 955
Artur Avatar asked Jan 05 '23 11:01

Artur


2 Answers

Here is an example on how to configure it when creating a flow. That should be similar to configure it directly with the job builder:

return new FlowBuilder<SimpleFlow>("name")
    .start(step1) //
    .next(step2).on(ExitStatus.FAILED.getExitCode()).to(errorStep)
    .from(step2).on(ALL_PATTERN).to(step3)
    .build();
like image 195
Hansjoerg Wingeier Avatar answered Jan 08 '23 01:01

Hansjoerg Wingeier


You can use 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());
    }
}

Then in your step

@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.

Some helpful links

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

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

like image 39
A0__oN Avatar answered Jan 08 '23 01:01

A0__oN