티스토리 뷰
반응형
의존성 추가
dependencies {
implementation("org.springframework.boot:spring-boot-starter-batch")
implementation("org.springframework.boot:spring-boot-starter-data-jpa") // JPA 사용 시
runtimeOnly("org.postgresql:postgresql") // 데이터베이스에 따라 변경
}
application.yml
spring:
// DB 정보는 알아서 적당히 바꾸시길
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: myuser
password: mypassword
driver-class-name: org.postgresql.Driver
batch:
jdbc:
initialize-schema: always # 처음 실행할 때만 always (테이블 자동 생성, 그 이후엔 never 권장)
BatchJobConfig
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@RequiredArgsConstructor
public class BatchJobConfig {
private final String JOB_NAME = "sampleJob";
private final String STEP_NAME = "sampleStep";
@Bean
public Job sampleJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder(JOB_NAME, jobRepository)
.incrementer(new RunIdIncrementer()) // 실행할 때마다 새로운 Job 인스턴스 생성
.start(sampleStep(jobRepository, transactionManager))
.build();
}
@Bean
public Step sampleStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder(STEP_NAME, jobRepository)
.tasklet(sampleTasklet(), transactionManager)
.build();
}
@Bean
public Tasklet sampleTasklet() {
return (contribution, chunkContext) -> {
System.out.println("Spring Batch (without @EnableBatchProcessing) 실행 완료!");
return RepeatStatus.FINISHED;
};
}
}
BatchRunner
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.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class BatchRunner implements CommandLineRunner {
private final JobLauncher jobLauncher;
private final Job sampleJob;
@Override
public void run(String... args) throws Exception {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis()) // 매번 실행되도록 설정
.toJobParameters();
jobLauncher.run(sampleJob, jobParameters);
}
}
요렇게 설정하고 서버 올리면 배치관련 테이블들이 생성되며 sampleJob이 처음 실행됨
그러면 기본적인 구성은 끝!
생성된 테이블 정보
테이블 명 | 설명 |
BATCH_JOB_INSTANCE | 배치 Job 실행 정보 저장 |
BATCH_JOB_EXECUTION | Job 실행 이력 저장 |
BATCH_JOB_EXECUTION_PARAMS | Job 실행 시 전달된 파라미터 저장 |
BATCH_JOB_EXECUTION_CONTEXT | Job 실행 컨텍스트(추가 정보) 저장 |
BATCH_STEP_EXECUTION | Step 실행 이력 저장 |
BATCH_STEP_EXECUTION_CONTEXT | Step 실행 컨텍스트(추가 정보) 저장 |
BATCH_STEP_EXECUTION_SEQ | Step 실행의 시퀀스 관리 (자동 증가 값) |
BATCH_JOB_EXECUTION_SEQ | Job 실행의 시퀀스 관리 (자동 증가 값) |
BATCH_JOB_SEQ | Job ID 관리 (자동 증가 값) |
스케쥴링으로 변경하기
application.yml
spring:
batch:
jdbc:
initialize-schema: never
job:
name: sampleJob # job 이름 설정
enabled: false # Job 실행을 스케줄러에게 위임하기 위하여 설정
EnableScheduling 추가
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
ScheduledBatchRunner
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class ScheduledBatchRunner {
private final JobLauncher jobLauncher;
private final Job sampleJob;
@Scheduled(cron = "*/10 * * * * ?") // 10초마다 실행
public void runSampleJob() throws Exception {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(sampleJob, jobParameters);
}
}
이렇게 설정 해주고 서버 올리면 콘솔에서 10초마다 실행되는 것을 확인 할 수 있다.
아까 생성된 테이블을 잠깐 써먹어보면 이렇게 확인도 가능하다.
select * from batch_job_execution;
반응형
'Back-end > Spring' 카테고리의 다른 글
Swagger Spring Boot (3.4.2) (0) | 2025.02.27 |
---|---|
@Autowired의 기본 간단 정리 (0) | 2022.08.04 |
SpringBoot에서 Swagger 설정하기(3.0 버전) (0) | 2022.07.30 |
JWT 구현하기 (0) | 2020.08.25 |
Spring Boot 간편 로그인 구현하기(with security & oauth2.0) (1) | 2020.08.24 |
댓글