Spring Batch ‐ 스프링 배치 실행(Step) - thought-corner/Backend-PlayGround GitHub Wiki
Tasklet
- 스프링 배치에서 제공하는
Step의 구현체로서Tasklet을 실행시키는 도메인 객체 RepeatTemplate를 사용해서Tasklet구문의 트랜잭션 경계 내에서 반복 실행한다.
Step내에서 구성되고 실행되는 도메인 객체로서 주로 단일 태스크를 수행하기 위한 것이다.TaskletStep에 의해 반복적으로 수행되며 반환값에 따라 계속 수행 혹은 종료한다.RepeatStatus- Tasklet의 반복 여부 상태 값(RepeatStatus.FINISHED / RepeatStatus.CONTINUABLE)
@FunctionalInterface
public interface Tasklet {
/**
* Given the current context in the form of a step contribution, do whatever is
* necessary to process this unit inside a transaction. Implementations return
* {@link RepeatStatus#FINISHED} if finished. If not they return
* {@link RepeatStatus#CONTINUABLE}. On failure throws an exception.
* @param contribution mutable state to be passed back to update the current step
* execution
* @param chunkContext attributes shared between invocations but not between restarts
* @return an {@link RepeatStatus} indicating whether processing is continuable.
* Returning {@code null} is interpreted as {@link RepeatStatus#FINISHED}
* @throws Exception thrown if error occurs during execution.
*/
@Nullable RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception;
}
RepeatStatus: 끝 혹은 계속 작업을 다시 실행StepContribution: 현재 단계가 얼마나 진행되었는지 기록하는 객체ChunkContext: 작업 수행에 필요한 정보가 담겨있는 객체. 외부에서 넘겨준 파라미터(JobParameter), 이전 단계에서 넘겨준 데이터(ExecutionContext)
❗while문으로 한 번에 처리하면 안되는 이유
- 100만건의 데이터를 처리하다가 중간에서 에러가 발생하면 while문으로 묶었을 경우 모든 데이터를 롤백해야 한다.
- Tasklet의
execute메서드는 한 번 수행할 때마다 하나의 트랜잭션을 만들어내는데 문제가 발생한 데이터만 롤백하면 된다.
트랜잭션 처리가 불필요한 배치
ResourcelessTransactionManager: 자원을 가지고 있지 않은 트랜잭션 매니저- 실제 DB와 연결되지 않은 껍데기만 가지는 트랜잭션 매니저로 스프링 배치가 동작하기 위해 형식적으로 필요한 트랜잭션 관리자의 역할을 한다.
- 다만 실제 DB의 Commit이나 Rollback을 수행하지 않는다.
startLimit & allowStartIfComplete
startLimit- Step의 실행 횟수를 조절할 수 있다.
- Step마다 설정할 수 있다.
- 설정 값을 초과해서 다시 실행하려고 하면 StartLimitExceededException 예외가 발생한다.
- start-limit의 default 값은 Integer.MAX_VALUE
allowStartIfComplete- 재시작 가능한 Job에서 Step의 이전 성공 여부와 상관없이 항상 Step을 실행하기 위한 설정
- 실행마다 유효성을 검증하는 Step이나 사전 작업이 꼭 필요한 Step
- 기본적으로 COMPLETED 상태를 가진 Step은 Job 재시작시 실행하지 않고 스킵한다.
- allow-start-if-complete가 true인 경우로 설정된 Step은 항상 실행한다.
TaskletStep 아키텍처
- 예외가 발생하면 이후로의 진행이 이루어지지 않는다.
RepeatStatus값에 따라 Step의 반복 여부가 정해진다.
JobStep
- Job에 속하는 Step 중 외부 Job을 포함하는 Step
- 외부의 Job이 실패하면 해당 Step 역시 실패하므로 최종 기본 Job 역시 실패하게 된다.
- 모든 메타 데이터는 기본 Job과 외부 Job별로 각각 저장된다.
- 커다란 시스템을 작은 모듈로 쪼개고 Job의 흐름을 관리하고자 할 때 사용할 수 있다.