본문 바로가기
spring

spring EventListener에서 @Async 비동기 적용

by 토망이 2023. 7. 31.

본 글에서는 EventListener에서 비동기 방식으로 @Async를 사용하는 방법을 다루겠습니다. EventListner에 대한 코드는 이전글을 참고해주세요.

spring event pub/sub 구현

 

spring event pub/sub 구현

본 글에서는 spring에서 ApplicationEventPublisher를 활용하여, 동일한 프로젝트 내에서 간단하게 event pub/sub 구조를 구현해보겠습니다. 원래 다른 서버와 pub/sub 구현을 위해서는, kafka 혹은 redis 등등을

dnl1029.tistory.com

 

- config

: spring에서 비동기를 사용하는 방법은 간단합니다. ThreadPoolTaskExecutor를 선언 후 Config 파일에서 Bean 등록만 해주면되는데, 같은 방식으로 MongoDB의 Asyncconfig를 사용할 수 있습니다.

@Configuration
public class EventListenerAsyncConfig {

    @Qualifier("eventListenerThreadExecutor")
    @Bean(name = "eventListenerThreadExecutor")
    public ThreadPoolTaskExecutor threadExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5); // 기본 thread 수
        threadPoolTaskExecutor.setMaxPoolSize(5); //최대 thread 수
        threadPoolTaskExecutor.setQueueCapacity(3); //기본 thread량 초과시 queue에 쌓이게
        threadPoolTaskExecutor.setThreadNamePrefix("eventListenerThreadPool-");
        threadPoolTaskExecutor.setAwaitTerminationSeconds(20);
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true); //graceful shutdown
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}

 

- SubService

@Service
@Slf4j
@RequiredArgsConstructor
public class EventSubService {

    @Qualifier("eventListenerThreadExecutor")
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Async("eventListenerThreadExecutor")
    @EventListener
    public void subscribe(EventDto eventDto) {
        log.info("EventSubService. event: {}", eventDto);
        log.info("thread / corePool : {}, maxPool : {}, QueueCapacity : {}, ActiveCount : {}",
                threadPoolTaskExecutor.getCorePoolSize(),
                threadPoolTaskExecutor.getMaxPoolSize(),
                threadPoolTaskExecutor.getQueueCapacity(),
                threadPoolTaskExecutor.getActiveCount());

    }

}

 

- Swagger 테스트

 

- 결과

 

DB Select쿼리가 오래걸릴때도, 위와 같이 동일한 방식으로 @Async 어노테이션만으로 간단하게 비동기 설정을 할수 있습니다.

댓글