Skip to content

SpringBoot에서 Background Thread 만들기

Jong cheol, Kim edited this page Jun 23, 2016 · 6 revisions

1.Event Listener

1.1 Event Listener 란

  • 어떠한 이벤트가 발생하면 호출되어 처리하는 객체.

1.2 Listener 사용법

  • 구현할 기능과 관련된 각종 인터페이스만 제공함으로 클래스는 구현해야함.

1.3 Listener 인터페이스 종류

ServletContextListener

  • 웹 어플리케이션의 시작과 종료시 자동으로 발생되는 이벤트를 수행하기 위한 메소드를 정의한 인터페이스이다.

    method name 설명
    contextInitialized(ServletContextEvent sce) : void 웹 컨테이너가 처음 구동될 때 실행되는 메소드
    contextDestoryed(ServletContextEvent sce) : void 웹 컨테이너가 종료될 때 실행되는 메소드

ServletContextAttributeListener

  • 컨테이너에 저장된 속성 값들의 변화가 있을 때 수행하기 위한 메소드를 정의한 인터페이스이다.

    method name 설명
    attributeAdded(ServletContextAttributeEvent scae) : void 새로운 속성 값이 추가될 때 실행되는 메소드
    attributeRemoved(ServletContextAttributeEvent scae) : void 속성 값이 제거될 때 실행되는 메소드
    attributeReplaced(ServletContextAttributeEvent scae) : void 속성 값이 변경될 때 실행되는 메소드

HttpSessionListener

  • HTTP 세션이 활성화 되거나 비활성화 되려할 때 혹은 속성 값들이 추가, 삭제, 변경될 경우 수행하기 위한 인터페이스

    method name 설명
    sessionCreated(HttpSession se) : void 세션이 생성되었을 경우 이 메소드가 실행
    sessionDestoryed(HttpSession se) : void 세션이 무효화 되었을 경우 이 메소드 실행

HttpSessionAttributeListener

  • HTTP 세션에 대한 속성 값이 변경되었을 경우 수행하기 위한 인터페이스

    method name 설명
    attributeAdded(HttpSessionBindingEvent e) : void 세션에 새로운 속성 값이 추가될 때 실행
    attributeRemoved(HttpSessionBindingEvent e) : void 세션의 속성 값이 제거될 실행
    attributeReplaced(HttpSessionBindingEvent e) : void 세션의 속성 값이 변경될 때 실행

HttpSessionActivationListener

  • 세션에 대한 내용이 새로 생성되어 세션이 활성화 되었을 때 발생하는 이벤트를 수행하기 위한 인터페이스

    method name 설명
    sessionDidActivate(HttpSessionEvent e) : void 세션이 활성화 될 때 실행
    sessionWillPassivate(HttpSessionEvent e) : void 세션이 비활성화 되려고 할 때 실행

HttpSessionBindingListener

  • 클라이언트의 세션 정보에 대한 바인딩이 이루어졌을 경우 감지되는 이벤트를 수행하기 위한 인터페이스

    method name 설명
    valueBound(HttpSessionBindingEvent e) : void 세션에 연결될 때 발생하는 이벤트를 실행
    valueUnBound(HttpSessionBindingEvnet e) : void 세션으로부터 연결이 해제될 때 발생하는 이벤트를 실행

2. Spring Boot Background Thread Listener & Main Class

Listener Thead

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class DaemonListener implements ServletContextListener, Runnable
{
    /** 작업을 수행할 thread */
    private Thread thread;
    private boolean isShutdown = false;

    /** context */
    private ServletContext sc;

    /** 작업을 수행한다 */
    public void startDaemon() {
        if (thread == null) {
            thread = new Thread(this, "Daemon thread for background task");
//            thread.setDaemon(true);
        }

        if (!thread.isAlive()) {
            thread.start();
        }
    }

    /** 스레드가 실제로 작업하는 부분 */
    public void run() {
        Thread currentThread = Thread.currentThread();

        while (currentThread == thread && !this.isShutdown) {
            try {
                System.out.println ("===================DaemonListener is running.===================");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println ("===================DaemonListener end.===================");
    }


    /** 컨텍스트 초기화 시 데몬 스레드를 작동한다 */
    public void contextInitialized (ServletContextEvent event) {
        System.out.println ("===================DaemonListener.contextInitialized has been called.===================");
        sc = event.getServletContext();
        startDaemon();
    }

    /** 컨텍스트 종료 시 thread를 종료시킨다 */
    public void contextDestroyed (ServletContextEvent event) {
        System.out.println ("===================DaemonListener.contextDestroyed has been called.===================");
        this.isShutdown = true;
        try
        {
            thread.join();
            thread = null;
        }
        catch (InterruptedException ie)
        {
            ie.printStackTrace();
        }
    }
}

Spring Boot Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.system.ApplicationPidFileWriter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class SampleSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SampleSpringBootApplication.class);
        application.addListeners(new ApplicationPidFileWriter());
        application.run(args);
    }
}