본문 바로가기

Web/spring

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

728x90

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

 

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

 

틀린 해석이 있다면 알려주세요 🪴


 

 

Configuring and Running a Job

 

Job 자체가 단순 컨테이너로 보일 수 있겠지만, 여기 있는 많은 구성의 옵션을 알고 있어야한다

또한 Job을 실행하는 방법과 해당 메타데이터를 저장하는 방법에 대한 많은 옵션을 고려해야한다

 

 

 

Configuring a Job

Restartability

Batch job 을 실행할 때 중요한 문제 중 하나는 재시작 시의 job 동작과 관련이 있다

JobExecution이 특정 JobInstance에 대해 이미 존재하는 경우 Job실행은 "restart"로 보게 된다

이상적으로 모든 작업이 중단된 위치에서 시작해야하겠지만 불가능한 시나리오일 수 있다

이 시나리오에서 새 JobInstance가 생성되었는지 확인하는 것은 전적으로 개발자가 컨트롤한다

Spring Batch에서는 이에 관한 약간의 기능을 제공하는데, 작업을 다시 시작해서는 안되나 항상 새 JobInstance를 일부로 실행시키려고 할 경우 해당 속성을 false로 설정할 수 있다

 

The following example shows how to set the restartable field to false in XML:

Example 1. XML Configuration
<job id="footballJob" restartable="false">
    ...
</job>
 

The following example shows how to set the restartable field to false in Java:

Example 2. Java Configuration
@Bean
public Job footballJob(JobRepository jobRepository) {
    return new JobBuilder("footballJob", jobRepository)
                     .preventRestart()
                     ...
                     .build();
}
 

 

restartable=false << job 재실행을 하지 않겠다는 의미

 

To phrase it another way, setting restartable to false means “this Job does not support being started again”. Restarting a Job that is not restartable causes a JobRestartException to be thrown. The following Junit code causes the exception to be thrown:

Job job = new SimpleJob();
job.setRestartable(false);

JobParameters jobParameters = new JobParameters();

JobExecution firstExecution = jobRepository.createJobExecution(job, jobParameters);
jobRepository.saveOrUpdate(firstExecution);

try {
    jobRepository.createJobExecution(job, jobParameters);
    fail();
}
catch (JobRestartException e) {
    // expected
}
 

The first attempt to create a JobExecution for a non-restartable job causes no issues. However, the second attempt throws a JobRestartException.

 

 

Intercepting Job Execution

Job 이 실행되는 동안 custom code를 실행할 수 있도록 lifecycle의 다양한 이벤트에 대한 알림을 받을 수 있다.

SimpleJob은 JobListener를 호출할 수 있도록 허용한다

public interface JobExecutionListener {

    void beforeJob(JobExecution jobExecution);

    void afterJob(JobExecution jobExecution);
}
 

You can add JobListeners to a SimpleJob by setting listeners on the job.

The following example shows how to add a listener element to an XML job definition:

Example 3. XML Configuration
<job id="footballJob">
    <step id="playerload"          parent="s1" next="gameLoad"/>
    <step id="gameLoad"            parent="s2" next="playerSummarization"/>
    <step id="playerSummarization" parent="s3"/>
    <listeners>
        <listener ref="sampleListener"/>
    </listeners>
</job>
 

The following example shows how to add a listener method to a Java job definition:

Example 4. Java Configuration
@Bean
public Job footballJob(JobRepository jobRepository) {
    return new JobBuilder("footballJob", jobRepository)
                     .listener(sampleListener())
                     ...
                     .build();
}
 

Note that the afterJob method is called regardless of the success or failure of the Job. If you need to determine success or failure, you can get that information from the JobExecution:

public void afterJob(JobExecution jobExecution){
    if (jobExecution.getStatus() == BatchStatus.COMPLETED ) {
        //job success
    }
    else if (jobExecution.getStatus() == BatchStatus.FAILED) {
        //job failure
    }
}
 

The annotations corresponding to this interface are:

  • @BeforeJob
  • @AfterJob

 

 

Inheriting from a Parent Job

 

작업 그룹이 유사하지만 동일하지 않은 구성을 공유하는 경우 구체적인 작업 인스턴스가 속성을 상속할 수 있는 "parent" 작업을 정의하는 것이 도움이 될 수 있다.

Java의 클래스 상속과 유사하게 "하위" Job은 해당 요소와 속성을 상위 항목과 결합한다.  다음 예제에서 baseJob은 리스너 목록만 정의하는 추상 Job 정의이다.

작업(job1)은 baseJob에서 리스너 목록을 상속하고 이를 자체 리스너 목록과 병합하여 두 개의 리스너와 하나의 단계(step1)가 있는 작업을 생성하는 구체적인 정의이다. 

 

<job id="baseJob" abstract="true">
    <listeners>
        <listener ref="listenerOne"/>
    <listeners>
</job>

<job id="job1" parent="baseJob">
    <step id="step1" parent="standaloneStep"/>

    <listeners merge="true">
        <listener ref="listenerTwo"/>
    <listeners>
</job>
 

 

A job declared in the XML namespace or using any subclass of AbstractJob can optionally declare a validator for the job parameters at runtime. This is useful when, for instance, you need to assert that a job is started with all its mandatory parameters. There is a DefaultJobParametersValidator that you can use to constrain combinations of simple mandatory and optional parameters. For more complex constraints, you can implement the interface yourself.

 

728x90