티스토리 뷰





반응형

의존성 추가

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;

반응형
댓글
반응형
최근에 달린 댓글
글 보관함
Total
Today
Yesterday
최근에 올라온 글
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31