Back-end
[Spring Batch] Spring Batch 구조 및 테스트
yeobi
2024. 6. 8. 20:01
- Spring Batch 구조
- JobRepository : 배치가 수행될 때 수행되는 메타 데이터를 관리하고 시작 시간, 종료 시간, Job의 상태 등 배치 수행 관련 데이터들이 저장된다.
- JobLauncher : Job을 실행시키는 역할
- Job : 하나의 배치 작업을 의미한다.
- Step : 세부 작업 내용을 처리한다. 하나의 Job에 처리를 위한 1개 이상의 Step이 단계별로 실행될 수 있다.
작업의 주 영역은 Job과 Step, Step 하위의 Reader, Processor, Writer에서 개발을 한다.
- Spring Batch 설정
build.gradle에 의존성 추가
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-batch'
}
application.properties 설정
# spring batch setting
# true : 실행시 등록된 job을 실행, false : 실행x
spring.batch.job.enabled=true
# 특정 job만 실행시킬 경우 default는 NONE으로
spring.batch.job.names=${job.name:NONE}
# 스프링 배치 메타데이터 테이블 자동 생성 설정
spring.batch.jdbc.initialize-schema=always
**주의**
@EnableBatchProcessing // 작성하면 Spring Batch 기본 설정이 백오프된다.
@SpringBootApplication
public class SpringbatchApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbatchApplication.class, args);
}
}
스프링 부트3, 스프링 배치5로 업데이트 되면서 main에 @EnableBatchProcessing 어노테이션을 넣으면 안 된다.
- 실행 테스트
job/HelloWorldJobConfig 클래스
@Configuration
@RequiredArgsConstructor
public class HelloWorldJobConfig extends DefaultBatchConfiguration {
@Bean
public Job helloWorldJob(JobRepository jobRepository, Step helloWorldStep) { // job 셍성
return new JobBuilder("helloWorldJob", jobRepository) // job의 이름 설정
.start(helloWorldStep) // 실행할 step 설정
.build();
}
@Bean
public Step helloWorldStep(JobRepository jobRepository, Tasklet helloWorldTasklet, PlatformTransactionManager platformTransactionManager) {
return new StepBuilder("helloWorldStep", jobRepository)
.tasklet(helloWorldTasklet, platformTransactionManager ).build(); // tasklet 실행
}
@Bean
public Tasklet helloWorldTasklet() {
return ((contribution, chunkContext) -> {
System.out.println("helloWorldTasklet"); // 수행할 작업
return RepeatStatus.FINISHED; // 작업이 끝난 후의 Status 설정
});
}
}
Tasklet이 가장 하위의 작업 단위이며 {Reader, Processor, Writer } 묶음으로 실행할 수도 있다.
DefaultBatchConfiguration은 기존의 @EnableBatchProcessing 가 하던 JobRepository, JobLauncher, StepScope, JobScope 등의 Bean을 등록하는 작업을 대신하는 class이다.
실행 결과
작업이 성공적으로 수행되었음을 알 수 있다.
- 스프링 배치 5 바뀐 점
https://alwayspr.tistory.com/49
Spring Batch 5 뭐가 달라졌나?
Spring Batch 4.0에서 약 5년의 세월이 흘러 Spring Batch 5.0으로 메이저 버전이 업데이트되었다. 어떤 기능들이 개선되고, 생겼는지 알아보도록 하자. 의존성 Spring Batch5는 Spring framework 6을 의존하기 때
alwayspr.tistory.com