ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Scheduler 구현
    [공부] 프로그래밍/Spring・Spring Boot (JAVA) 2024. 4. 9. 12:03

     

    Scheduler 구현
    @Component
    @ComponentScan({"co.test1.test2"})
    //@EnableRetry
    public class SchedulerTask {
        
        private static final Logger LOG = LoggerFactory.getLogger(SchedulerTask.class);
    
        public static void main(String[] args) {
            String jobclass = args[0];
            
            try {
                JobDetail job = JobBuilder.newJob(execJob(jobclass))
                        .withIdentity("job1", "group1")
                        .build();
                ApplicationContext context = new AnnotationConfigApplicationContext((co.test1.test2.test3.SchedulerTask.class));
                ApplicationContextUtil appUtil = new ApplicationContextUtil();
                appUtil.setApplicationContext(context);
    
                Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity("trigger1", "group1")
                        .startNow()
                        .build();
    
                Scheduler scheduler = null;
                
                try {
                    scheduler = StdSchedulerFactory.getDefaultScheduler();
                    scheduler.scheduleJob(job, trigger);
                    scheduler.start();
                } catch (SchedulerException e) {
                    throw new RuntimeException(e);
                }
    
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                try {
                    scheduler.shutdown(true);
                    stop();
                } catch (SchedulerException e) {
                    throw new RuntimeException(e);
                }
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error(e.getMessage(), e);
            }
        }
    
        public static void stop() {
            System.exit(0);
        }
    
        private static Class<? extends Job> execJob(String jobclass) {
            return co.test1.test2.Test01.controller.Test01Controller.class;
        }
    }
    ▷ @Component
    Spring Boot에서는 클래스가 Spring 컴포넌트임을 나타내기 위해 사용됩니다. Spring 컴포넌트는 Spring 컨테이너에 의해 관리되는 Java 클래스로, 주로 의존성 주입, 관점 지향 프로그래밍 및 기타 Spring 기능과 같은 작업에 사용됩니다. 클래스가 @Component로 주석 처리되면 Spring이 자동으로 해당 클래스를 애플리케이션 콘텍스트에 빈으로 등록합니다. 이는 Spring이 클래스를 인스턴스화하고 그 수명주기를 관리하여 의존성 주입 및 기타 Spring 기능에 사용할 수 있도록 만듭니다.

    ▷ @ComponentScan({"co.jp.test1.test2"})
    Spring이 @Component, @Service, @Repository 등과 같은 Spring 컴포넌트를 발견하기 위해 스캔해야 하는 패키지를 지정하는 데 사용됩니다.

    @EnableRetry
    스프링 프레임워크에서 사용되는 주석으로, @Retryable로 주석 처리된 메서드에 대한 재시도 기능을 활성화합니다. 이 주석은 일시적인 오류, 예를 들어 네트워크 타임아웃, 데이터베이스 연결 문제 또는 기타 일시적인 오류가 발생했을 때 특정 작업을 자동으로 다시 시도해야 하는 경우에 사용됩니다.
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.retry.annotation.EnableRetry;
    
    @Configuration
    @EnableRetry
    public class RetryConfig {
    
        @Bean
        public MyService myService() {
            return new MyService();
        }
    }
    @Service
    public class MyService {
        @Retryable(value = {IOException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))
        public void retryOperation() throws IOException {
            // IOException이 발생할 수 있는 코드
        }
    }

    main 메소드

    1. Job 생성 및 설정:

    JobDetail job = JobBuilder.newJob(selectExecJob(jobclass))
                    .withIdentity("job1", "group1")
                    .build();

     

    JobBuilder.newJob() 메서드는 Quartz JobBuilder 클래스에서 새 작업을 생성합니다.
    ・ selectExecJob(jobclass)는 어떤 유형의 작업을 선택할지에 따라 사용자가 정의한 메서드입니다.
    ・ withIdentity("job1", "group1")은 작업에 고유한 식별자를 부여합니다. 여기서는 "job1"이라는 이름을 "group1" 그룹 내에서 사용합니다.
    ・ build()는 작업을 완성하고 생성합니다.

    2. Spring ApplicationContext 생성:

    ApplicationContext context = new AnnotationConfigApplicationContext((co.test1.test2.test3.SchedulerTask.class));
    ・ AnnotationConfigApplicationContext는 스프링 컨텍스트를 구성하는 방법 중 하나입니다. Java 기반의 설정 클래스를 사용하여 스프링 빈을 등록하고 관리할 수 있습니다.
    ・ (co.jp.test1.test2.test3.SchedulerTask.class)는 설정 클래스의 위치를 나타냅니다. 이 설정 클래스는 스프링 애플리케이션 콘텍스트를 구성하고 필요한 빈을 등록하는 역할을 할 것입니다.

    3. ApplicationContextUtil을 사용하여 ApplicationContext 설정:

    ApplicationContextUtil appUtil = new ApplicationContextUtil();
    appUtil.setApplicationContext(context);
    ・ ApplicationContextUtil 클래스의 객체를 생성하고 setApplicationContext() 메서드를 사용하여 애플리케이션 컨텍스트를 설정합니다. 이는 애플리케이션의 다른 부분에서 해당 애플리케이션 컨텍스트를 사용할 수 있도록 해줍니다.

    4. Trigger 생성 및 설정:

    Trigger trigger = TriggerBuilder.newTrigger()
                      .withIdentity("trigger1", "group1")
                      .startNow()
                      .build();
    ・ TriggerBuilder.newTrigger() 메서드는 Quartz의 TriggerBuilder 클래스에서 새로운 트리거를 생성합니다.
    withIdentity("trigger1", "group1")은 트리거에 고유한 식별자를 부여합니다. 여기서는 "trigger1"이라는 이름을 "group1" 그룹 내에서 사용합니다.
    ・ startNow()는 트리거를 즉시 시작하도록 설정합니다.
    ・ build()는 트리거를 완성하고 생성합니다.

    트리거(Trigger) :
    특정 테이블에 INSERT, DELETE, UPDATE 같은 DML 문이 수행되었을 때, 데이터베이스에서 자동으로 동작하도록 작성된 프로그램입니다. 즉 사용자가 직접 호출하는 것이 아니라, 데이터베이스에서 자동적으로 호출하는 것

    5. Scheduler 설정:

    Scheduler scheduler = null;

    6. 스케줄러 가져오기, 예약, 시작:

    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
    } catch (SchedulerException e) {
        throw new RuntimeException(e);
    }

    7. 스케줄러 종료, 중지:

    try {
        scheduler.shutdown(true);
        stop();
    } catch (SchedulerException e) {
        throw new RuntimeException(e);
    }

     

    stop 메소드
    public static void stop() {
        System.exit(0);
    }
    ・ stop() 메서드는 정적(static)으로 선언되어 있으므로 어디서든 호출할 수 있습니다.
    ・ 이 메서드 내부에서는 System.exit(0)을 호출하여 JVM(Java Virtual Machine)을 종료합니다. 여기서 0은 정상 종료를 의미합니다.

     

    execJob 메소드
    private static Class<? extends Job> execJob(String jobclass) {
        return co.jp.test1.test2.Test01.controller.Test01Controller.class;
    }
    ・ Class<? extends Job>은 Job 클래스 또는 Job 클래스의 하위 클래스의 클래스 객체를 나타냅니다.
    ・ 이 메서드는 Job 클래스나 Job 클래스의 하위 클래스 중 하나의 클래스 객체를 반환합니다.

    Test01Controller
    ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
    test01Service = applicationContext.getBean(Test01Service.class);
    test01Service.exec_Batch();
    ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
    여기서 ApplicationContextUtil.getApplicationContext()는 애플리케이션 콘텍스트를 가져오는 메서드입니다. 그리고 그 애플리케이션 콘텍스트를 applicationContext 변수에 할당합니다. 애플리케이션 콘텍스트란 Spring 프레임워크에서 사용하는 중요한 객체로, 스프링 애플리케이션의 구성 요소들을 관리하는 역할을 합니다.

    ・ test01Service = applicationContext.getBean(Test01Service.class);
    여기서는 applicationContext에서 Test01Service 클래스 타입의 빈(bean)을 가져오는 부분입니다. 그리고 이를 test01Service 변수에 할당합니다.

    ・ test01Service.exec_Batch();
    이 코드는 test01Service 변수에 할당된 빈의 exec_Batch() 메서드를 실행하는 부분입니다.

    요약하자면, 이 코드는 Spring 프레임워크를 사용하여 애플리케이션 콘텍스트에서 데이터 서비스 빈을 가져와서 작업을 실행하는 것으로 보입니다.

     

    '[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글

    Spring Batch 구현 - 2  (0) 2024.04.18
    Spring Batch 구현 - 1  (0) 2024.04.16
    MessageSource 처리  (0) 2024.04.04
    ApplicationContext 란  (0) 2024.04.03
    세션 처리  (0) 2024.04.03
Designed by Tistory.