본문 바로가기

Web/spring

[Spring Batch] Configuring and Running a Job - (5) Running a Job

728x90

https://docs.spring.io/spring-batch/docs/current/reference/html/job.html#runningAJob

 

Configuring and Running a Job

If a group of Jobs share similar but not identical configurations, it may help to define a “parent” Job from which the concrete Job instances can inherit properties. Similar to class inheritance in Java, a “child” Job combines its elements and attr

docs.spring.io

 

틀린 해석이 있다면 알려주세용 🍟

 


 

 

 

Running a Job

batch job requires 을 외한 최소한의 작업은 바로 Job과 JobLauncheer 두가지가 필요하다

둘 다 동일한 context 또는 다른 context 내에 포함될 수 있다

예를 들어서, commandLine에서 job 을 시작했을 때 각 작업에 대해 새 JVM이 인스턴스화 된다

따라서 모든 작업에는 자체 JobLaucher가 있다

그러나 HttpRequest scope 내에 있는 웹 컨테이너 내에서 실행하는 경우에는 일반적으로 시작하기 위한 여러 요청을 호출하는 하나의 JobLauncher(configured for asynchronous job launching)가 있다

 

 

Running Jobs from the Command Line

엔터프라이즈 스케줄러에서 작업을 실행하려는 경우 명령줄이 기본 인터페이스이다.

이는 대부분의 스케줄러(NativeJob을 사용하지 않는 한 Quartz 제외)가 주로 셸 스크립트로 시작되는 운영 체제 프로세스와 직접 작동하기 때문이다.

Perl, Ruby 또는 Ant 또는 Maven과 같은 빌드 도구와 같은 셸 스크립트 외에 Java 프로세스를 시작하는 방법은 여러 가지가 있다.

그러나 대부분의 사람들이 쉘 스크립트에 익숙하기 때문에 이 예제에서는 쉘 스크립트에 중점을 둔다.

 

 

 

 

The CommandLineJobRunner

작업을 시작하는 스크립트는 JVM(Java Virtual Machine)을 시작해야 하므로 기본 진입점 역할을 하는 기본 메서드가 있는 클래스가 있어야 한다. Spring Batch는 CommandLineJobRunner라는 목적을 수행하는 구현을 제공하는데 이는 응용 프로그램을 부트스트랩하는 방법 중 하나이다. Java 프로세스를 시작하는 방법에는 여러 가지가 있으며 이 클래스를 결정적인 것으로 간주해서는 안된다. CommandLineJobRunner는 네 가지 작업을 수행한다.

  • Load the appropriate ApplicationContext.
  • Parse command line arguments into JobParameters.
  • Locate the appropriate job based on arguments.
  • Use the JobLauncher provided in the application context to launch the job.

All of these tasks are accomplished with only the arguments passed in.

The following table describes the required arguments:

 

위의 4가지 작업은 전달된 CommandLineJobRunner 인수로만 수행 된다

CommandLineJobRunner arguments

jobPath The location of the XML file that is used to create an ApplicationContext. This file should contain everything needed to run the complete Job.
jobName The name of the job to be run.
These arguments must be passed in, with the path first and the name second. All arguments after these are considered to be job parameters, are turned into a JobParameters object, and must be in the format of name=value.

 

 

xml로 정의된 작업 매개변수

<bash$ java CommandLineJobRunner endOfDayJob.xml endOfDay schedule.date=2007-05-05,java.time.LocalDate

java

<bash$ java CommandLineJobRunner io.spring.EndOfDayJobConfiguration endOfDay schedule.date=2007-05-05,java.time.LocalDate

 

 기본적으로 CommandLineJobRunner는 키/값 쌍을 식별 작업 매개변수로 암시적으로 변환하는 DefaultJobParametersConverter를 사용한다.

그러나 각각 true 또는 false 접미사를 추가하여 식별하는 작업 매개변수와 식별하지 않는 작업 매개변수를 명시적으로 지정할 수 있다.

<bash$ java CommandLineJobRunner endOfDayJob.xml endOfDay \
                                 schedule.date=2007-05-05,java.time.LocalDate,true \
                                 vendor.id=123,java.lang.Long,false
 
 
<bash$ java CommandLineJobRunner io.spring.EndOfDayJobConfiguration endOfDay \
                                 schedule.date=2007-05-05,java.time.LocalDate,true \
                                 vendor.id=123,java.lang.Long,false
 

JobParametersConverter 를 커스텀하여 재정의 할 수 있다

 

위의 예제는 일반적으로 Spring Batch에서 배치작업을 실행하는 것에 더 많은 요구 사항이 있기 때문에 매우 단순하지만,

CommandLineJobRunner의 두 가지 주요 요구 사항인 Job 및 JobLauncher를 보여주고 있다

 

 

Exit Codes

명령줄에서 배치 작업을 시작할 때 엔터프라이즈 스케줄러가 자주 사용된다.

대부분의 스케줄러는 상당히 멍청하며 프로세스 수준에서만 작동한다.

이는 일부 운영 체제 프로세스(예: 호출하는 셸 스크립트)에 대해서만 알고 있음을 의미한다.

이 시나리오에서 작업의 성공 또는 실패에 대해 스케줄러와 다시 통신하는 유일한 방법은 리턴 코드를 통해서이다.

반환 코드는 실행 결과를 나타내기 위해 프로세스가 스케줄러에 반환하는 숫자이다.

가장 간단한 경우 0은 성공이고 1은 실패로 본다.

 

그러나 "작업 A가 4를 반환하면 작업 B를 시작하고 5를 반환하면 작업 C를 시작합니다."와 같은 더 복잡한 시나리오가 있을 수 있다.

이러한 유형의 동작은 스케줄러 수준에서 구성되지만 Spring Batch와 같은 처리 프레임워크가 특정 배치 작업에 대한 종료 코드의 숫자 표현을 반환하는 방법을 제공하는 것이 중요하다.

Spring Batch에서 이것은 5장에서 자세히 다루는 ExitStatus 내에 캡슐화된다.

종료 코드를 논의하기 위해 알아야 할 유일한 중요한 사항은 ExitStatus가 프레임워크에 의해 설정된 종료 코드 속성을 가지고 있다.

JobLauncher에서 반환된 JobExecution의 일부로 반환됩니다.

 

The CommandLineJobRunner converts this string value to a number by using the ExitCodeMapper interface:

public interface ExitCodeMapper {

    public int intValue(String exitCode);

}

 

 

ExitCodeMapper의 필수 계약은 문자열 종료 코드가 주어지면 숫자 표현이 반환된다는 것이다.

Job Runner에서 사용하는 기본 구현은 완료에 대해 0, 일반 오류에 대해 1, 제공된 컨텍스트에서 Job을 찾을 수 없는 것과 같은 Job Runner 오류에 대해 2를 반환하는 SimpleJvmExitCodeMapper이다.

위의 세 값보다 더 복잡한 값이 필요한 경우 ExitCodeMapper 인터페이스의 사용자 정의 구현을 제공해야 한다.

CommandLineJobRunner는 ApplicationContext를 생성하는 클래스이므로 'wired together'할 수 없으므로 덮어써야 하는 모든 값은 자동으로 연결되어야 한다.

이는 ExitCodeMapper의 구현이 BeanFactory 내에서 발견되면 컨텍스트가 생성된 후 러너에 주입됨을 의미한다.

고유한 ExitCodeMapper를 제공하기 위해 수행해야 하는 모든 작업은 구현을 루트 수준 빈으로 선언하고 실행기에 의해 로드되는 ApplicationContext의 일부인지 확인한다.

 

 

Running Jobs from within a Web Container

Historically, offline processing (such as batch jobs) has been launched from the command-line, as described earlier. However, there are many cases where launching from an HttpRequest is a better option. Many such use cases include reporting, ad-hoc job running, and web application support. Because a batch job (by definition) is long running, the most important concern is to launch the job asynchronously:

Asynchronous Job Launcher Sequence From Web Container

 

 launch asynchronously 비동기 적으로 시작하도록 구성 된 JobLauncher를 사용하여 Job을 시작하고 즉시 JobExcution을 반환시킨다

작업이 아직 실행 중일 수 있으나 이 nonblocking behavior 를 통해 컨트롤러가 즉시 반환할 수 있고

이는 HttpRequest를 처리할 때 필요하다

 

@Controller
public class JobLauncherController {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job job;

    @RequestMapping("/jobLauncher.html")
    public void handle() throws Exception{
        jobLauncher.run(job, new JobParameters());
    }
}

 

 

 

 

 

728x90