BackEnd/Spring Batch
24. FaultTolerant
hanseom
2022. 1. 4. 22:50
반응형
Spring Batch는 Job 실행 중에 오류가 발생할 경우 장애를 처리하기 위한 기능을 제공하며 이를 통해 복원력을 향상시킬 수 있습니다. 오류가 발생해도 Step이 즉시 종료되지 않고 Retry 혹은 Skip 기능을 활성화 함으로써 내결함성 서비스가 가능하도록 합니다. FaultTolerant 구조는 청크 기반의 프로세스 기반 위에 Skip과 Retry 기능이 추가되어 재정의 되어 있습니다.
- Skip: ItemReader / ItemProcessor / ItemWriter에 적용할 수 있습니다.
- Retry: ItemProcessor / ItemWriter에 적용할 수 있습니다.
API

package io.springbatch.springbatchlecture;
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.*;
import org.springframework.batch.item.adapter.ItemWriterAdapter;
import org.springframework.batch.item.support.ClassifierCompositeItemProcessor;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.batch.item.support.builder.CompositeItemProcessorBuilder;
import org.springframework.batch.repeat.CompletionPolicy;
import org.springframework.batch.repeat.RepeatCallback;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.repeat.exception.SimpleLimitExceptionHandler;
import org.springframework.batch.repeat.policy.SimpleCompletionPolicy;
import org.springframework.batch.repeat.policy.TimeoutTerminationPolicy;
import org.springframework.batch.repeat.support.RepeatTemplate;
import org.springframework.classify.PatternMatchingClassifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequiredArgsConstructor
@Configuration
public class FaultTolerantConfiguration {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
@Bean
public Job job() throws Exception {
return jobBuilderFactory.get("batchJob")
.incrementer(new RunIdIncrementer())
.start(step1())
.build();
}
@Bean
public Step step1() throws Exception {
return stepBuilderFactory.get("step1")
.<String, String>chunk(5)
.reader(new ItemReader<String>() {
int i = 0;
@Override
public String read() {
i++;
if(i == 1) {
throw new IllegalArgumentException("skip");
}
return i > 3 ? null : "item" + i;
}
})
.processor((ItemProcessor<String, String>) item -> {
throw new IllegalStateException("retry");
// return item;
})
.writer(items -> System.out.println(items))
.faultTolerant()
.skip(IllegalArgumentException.class)
.skipLimit(1)
.retry(IllegalStateException.class)
.retryLimit(2)
.build();
}
@Bean
public SimpleLimitExceptionHandler simpleLimitExceptionHandler(){
return new SimpleLimitExceptionHandler(3);
}
}
[참고자료]
반응형