Akashic Records

Spring Batch Job을 REST API로 실행하기 본문

Spring.io

Spring Batch Job을 REST API로 실행하기

Andrew's Akashic Records 2023. 4. 4. 22:15
728x90

REST API를 사용하여 Spring Batch Job을 실행하려면, 우선 컨트롤러를 만들어 Job을 실행할 수 있는 엔드포인트를 생성해야 합니다. 아래 예제에서는 Spring Boot 기반의 프로젝트에서 JobLauncher를 주입하여 Job을 실행하는 방법을 보여줍니다.

컨트롤러 생성:

import java.util.Random;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BatchController {

	@Autowired
	private JobLauncher jobLauncher;

	@Autowired
	private ApplicationContext context;

	@PostMapping("/batchs/{batchJobName}")
	public ResponseEntity<?> authenticateUser(@PathVariable String batchJobName, @RequestBody String jobParams)
			throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
			JobParametersInvalidException {

		Job jobToRun = (Job) context.getBean(batchJobName); // 어플리케이션 컨텍스트에서 Job 빈을 가져옴

		JobParameters jobParameters = new JobParametersBuilder().addString("key", new Random().nextLong() + "")
				.addString("params", jobParams).toJobParameters();
		JobExecution jobExecution = jobLauncher.run(jobToRun, jobParameters);

		return ResponseEntity.ok(jobExecution.toString());
	}

}


이제 REST API를 사용하여 Job을 실행할 수 있습니다. 예를 들어, 다음과 같이 curl 명령어를 사용하여 해당 엔드포인트를 호출할 수 있습니다.

curl --location 'http://localhost:8080/batchs/myJob' \
--header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTY4MDU5NTA0MywiZXhwIjoxNjgwNTk4NjQzfQ.M91f3cFZQp9tBEZoOlJoJMtJpHa2c-KtZaRN5x-enluYzM9FoWl6RIxqYOuMDpja31IwTfNJM3EX1EtsLd7oZw' \
--header 'Content-Type: application/json' \
--data '{"user":"myname"}'


이 예제에서는 sampleJob이라는 Job 인스턴스를 실행하고 있습니다. 해당 Job은 파라미터로 param을 사용하며, /start-job 엔드포인트를 통해 전달받습니다.

위의 예제를 사용하여 REST API를 통해 Spring Batch Job을 실행할 수 있습니다. 당연히 컨트롤러 내부의 로직을 변경하여 다양한 작업 및 구성을 수행할 수 있습니다.

728x90
Comments