it-day/springboot
Spring Batch(tasklet)
별지킴Lee
2023. 11. 27. 13:03
JobBuilderFactory : Job을 생성하는 빌더 팩토리
StepBuilderFactory : Step을 생성하는 빌더 팩토리
TestBatchJobConfig.java
@RequiredArgsConstructor
@Configuration
@Slf4j
public class TestBatchJobConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
public static final String JOB_NAME = " TestBatchJob";
@Autowired
private final TestBatchService testBatchService;
@Bean(name = JOB_NAME)
public Job TestJob() {
return jobBuilderFactory
.get(JOB_NAME)
.incrementer(new RunIdIncrementer()) //incremeter을 통해 같은 Job명, Job Parameter로 실행되는 Job이 중복실행될 수 있도록 설정할 수 있다.
.preventRestart() //preventRestart를 통해 중간에 실패한 Job의 경우 실패지점 재시작하지 못하도록 설정할 수 있다.
.listener(jobExecutionListener())
.start(TestTaskletStep())
.build();
}
// 필수 정의부분 templateTaskletStep -> 배치업무에 맞게 이름 정의 xxxTaskletStep
@Bean(name = JOB_NAME + "_step")
@JobScope
public Step TestTaskletStep() {
return stepBuilderFactory
.get(JOB_NAME +"_step")
.tasklet(TestTasklet())
.build();
}
@Bean(name = JOB_NAME + "_tasklet")
@StepScope
public MethodInvokingTaskletAdapter TestTasklet() {
MethodInvokingTaskletAdapter adapter = new MethodInvokingTaskletAdapter();
adapter.setTargetObject( testBatchService );
adapter.setTargetMethod("testMet"); // TestBatchService .java의 testMet 메서드
return adapter;
}
@JobScope
@Bean
public JobExecutionListener jobExecutionListener() {
return new JobExecutionListener() {
@Override
public void beforeJob(JobExecution jobExecution) {
System.out.println(JOB_NAME + " Start.");
}
@Override
public void afterJob(JobExecution jobExecution) {
long time = jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime();
System.out.println("==========================================");
System.out.println("총 소요된 시간 : " + time);
System.out.println("==========================================");
}
};
}
}
TestBatchService.java
@Slf4j
@Service
public class TestBatchService extends BaseComponent {
public void testMet () throws Exception{
for(int idx = 0; idx < 10; idx ++){
logger.info("[idx] = " + idx);
}
}
}
BaseComponent.java (로그용)
public class BaseComponent {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
protected LogUtils logger = new LogUtils(LOGGER);
}
실행법(로컬)
해당 app의 Arguments에
--job.name= job이름