Spring Batch에서 트리거 없이 실행하는 방법

러블리소피·2025년 1월 2일

Spring Batch는 JobLauncher를 통해 배치 작업(Job)을 실행할 수 있도록 설계되어 있습니다.
Spring Boot 애플리케이션 시작 시 배치를 바로 실행하려면 CommandLineRunner를 구현합니다.
REST 엔드포인트를 통해 특정 시점에 배치를 실행할 수도 있습니다.

1. CommandLineRunner로 애플리케이션 시작 시 실행

Spring Boot 애플리케이션 시작 시 배치를 바로 실행하려면 CommandLineRunner를 구현합니다.

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class BatchRunner implements CommandLineRunner {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job myJob;

    @Override
    public void run(String... args) throws Exception {
        // 파라미터 추가 (필요한 경우)
        JobExecution execution = jobLauncher.run(myJob, 
            new org.springframework.batch.core.JobParametersBuilder()
                .addLong("timestamp", System.currentTimeMillis())
                .toJobParameters()
        );

        // 실행 상태 확인
        System.out.println("Job Execution Status: " + execution.getStatus());
    }
}

2. REST API로 배치 실행

package shop.safere.marketzzin.v2.batch.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v2/batches")
@RequiredArgsConstructor
public class BatchController {

    private final JobLauncher jobLauncher;
    private final Job smartDeliveryStatusJob;

    @GetMapping("/smartDeliveryStatus")
    public void runSmartDeliveryStatus() {
        try {
            JobParameters jobParameters = new JobParametersBuilder()
                    .addLong("time", System.currentTimeMillis()) // 고유한 파라미터 추가
                    .toJobParameters();

            jobLauncher.run(smartDeliveryStatusJob, jobParameters);
        } catch (Exception e) {
            // Exception handling can be added as necessary
            e.printStackTrace();
        }
    }
}

3. 실행 시 주의사항

  • 고유 파라미터 필요
    Spring Batch는 동일한 파라미터로 배치를 중복 실행하지 않습니다. 따라서 JobParameters에 System.currentTimeMillis()와 같은 고유 값을 추가해야 합니다.

  • 배치 상태 확인
    배치 실행 상태를 확인하려면 JobExecution.getStatus()를 확인하세요.

  • 비동기 실행 (옵션)
    동기식 실행 대신 비동기로 실행하려면 별도의 스레드를 생성하거나 Spring의 @Async를 사용할 수 있습니다.

4. 장점

  • 스케줄러 없이 배치를 즉시 실행 가능.
  • 원하는 시점에서 유연하게 배치 실행.
  • 실행 환경(클라이언트, 서버, 테스트 등)에 구애받지 않음.

결론

이 2가지 방법은 개발 및 테스트 단계에서도 유용하며, 배치의 동작을 즉시 확인할 때 적합합니다.

profile
발전하는 개발자가 되고싶어요

0개의 댓글