IT/development

[springBoot] spring batch scheduler modularization (feat. DB)

알 수 없는 사용자 2023. 11. 13. 18:46
반응형

목차

    아래 포스팅에서 이어진 내용입니다.

     

    [springBoot] spring batch scheduler jpaRead/Writer (feat. DB)

    목차 아래 포스팅에서 이어진 내용입니다. [springBoot] spring scheduler simpleBatch (feat. scheduler) 목차 Batch1 🙂 package com.dev.lsy.springbatchlog.batch; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; impor

    yaga.tistory.com


    job의 step의 tasklet class 별도 생성, tasklet에서 서비스 호출하는 예제(살짝 모듈화)

    EmpBatchConfig 🙂

    package com.dev.lsy.springbatchex10.batch.config.batch;
    
    import com.dev.lsy.springbatchex10.batch.emp.service.EmpService;
    import com.dev.lsy.springbatchex10.batch.item.EmpTaskLet;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.batch.core.Job;
    import org.springframework.batch.core.Step;
    import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
    import org.springframework.batch.core.configuration.annotation.JobScope;
    import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
    import org.springframework.batch.core.configuration.annotation.StepScope;
    import org.springframework.batch.core.step.tasklet.Tasklet;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Slf4j
    @RequiredArgsConstructor
    @Configuration
    public class EmpBatchConfig {
    
        private final JobBuilderFactory jobBuilderFactory;
        private final StepBuilderFactory stepBuilderFactory;
        private final EmpService empService;
    
        @Bean
        public Job empBatchjob() {
            return jobBuilderFactory.get("empBatchjob")
                    .start(empBatchStep())
                    .build();
        }
    
        @Bean
        @JobScope
        public Step empBatchStep() {
            return stepBuilderFactory.get("empBatchStep")
                    .tasklet(empTask(empService))
                    .build();
        }
    
        @Bean
        @StepScope
        public Tasklet empTask(EmpService empService) {
            return new EmpTaskLet(empService);
        }
    }

    Emp 🙄

    package com.dev.lsy.springbatchex10.batch.emp.model;
    
    import lombok.*;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Getter
    @Setter
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    @Entity
    public class Emp {
    
        @Id
        private Long empNo;
        private String eName;
    }

    EmpRepository 🤗

    package com.dev.lsy.springbatchex10.batch.emp.repository;
    
    import com.dev.lsy.springbatchex10.batch.emp.model.Emp;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface EmpRepository extends JpaRepository<Emp, Long> {
    }

    EmpService 😎

    package com.dev.lsy.springbatchex10.batch.emp.service;
    
    import com.dev.lsy.springbatchex10.batch.emp.model.Emp;
    import com.dev.lsy.springbatchex10.batch.emp.repository.EmpRepository;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    @Slf4j
    @RequiredArgsConstructor
    public class EmpService {
    
        private final EmpRepository empRepository;
    
        /**
         * 사원목록 조회 
         * @return
         */
        public List<Emp> getEmpList() {
            return empRepository.findAll();
        }
    }

    Scheduler 😅

    package com.dev.lsy.springbatchex10.batch.schduler;
    
    import lombok.RequiredArgsConstructor;
    import org.springframework.batch.core.Job;
    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.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.time.LocalDateTime;
    
    @Component
    @EnableScheduling   //이게 있어야 애플리케이션 종료가 안됨
    @RequiredArgsConstructor
    public class Scheduler {
    
        private final JobLauncher jobLauncher;
        private final Job empBatchjob;
    	
        //스케줄은 상황에 맞게 수정
        @Scheduled(cron = "0 05 17 * * *")
        public void excuteScheduler() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
            jobLauncher.run(empBatchjob, new JobParametersBuilder()
                    .addString("date", LocalDateTime.now().toString())
                    .toJobParameters()
            );
        }
    }

     

    EmpTasklet 🤑

    package com.dev.lsy.springbatchex10.batch.item;
    
    
    import com.dev.lsy.springbatchex10.batch.emp.model.Emp;
    import com.dev.lsy.springbatchex10.batch.emp.service.EmpService;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.batch.core.ExitStatus;
    import org.springframework.batch.core.StepContribution;
    import org.springframework.batch.core.StepExecution;
    import org.springframework.batch.core.StepExecutionListener;
    import org.springframework.batch.core.scope.context.ChunkContext;
    import org.springframework.batch.core.step.tasklet.Tasklet;
    import org.springframework.batch.repeat.RepeatStatus;
    
    import java.util.List;
    
    @Slf4j
    @RequiredArgsConstructor
    public class EmpTaskLet implements Tasklet, StepExecutionListener {
    
        private final EmpService empService;
    
        @Override
        public void beforeStep(StepExecution stepExecution) {
            log.debug("=========================== Before EmpBatchjob ===========================");
        }
    
        //단순히 로그 출력
        @Override
        public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
            List<Emp> empList = empService.getEmpList();
            empList.forEach(emp -> {
                log.debug("emp ==> [{}]", emp);
            });
            return RepeatStatus.FINISHED;
        }
    
        @Override
        public ExitStatus afterStep(StepExecution stepExecution) {
            log.debug("=========================== End EmpBatchjob ===========================");
            return ExitStatus.COMPLETED;
        }
    
    }

    개인 스터디 기록을 메모하는 공간이라 틀린점이 있을 수 있습니다.

    틀린 점 있을 경우 댓글 부탁드립니다.


    다음 내용

     

    [springBoot] spring batch preventRestart option

    목차 아래 포스팅에서 이어진 내용입니다. [springBoot] spring batch scheduler modularization (feat. DB) 목차 아래 포스팅에서 이어진 내용입니다. [springBoot] spring batch scheduler jpaRead/Writer (feat. DB) 목차 아래 포

    yaga.tistory.com

    반응형