본 글에서는 EventListener에서 비동기 방식으로 @Async를 사용하는 방법을 다루겠습니다. EventListner에 대한 코드는 이전글을 참고해주세요.
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 어노테이션만으로 간단하게 비동기 설정을 할수 있습니다.
'spring' 카테고리의 다른 글
spring Mock Test (0) | 2024.03.12 |
---|---|
spring cloud config로 yml파일 배포없이 변경해보기 (0) | 2023.07.23 |
spring event pub/sub 구현 (0) | 2023.07.22 |
spring application.yml파일 설정값 적용 (0) | 2023.07.21 |
spring jwt 인증인가 인터셉터 만들기 (0) | 2023.07.08 |
spring 쓰레드로컬(ThreadLocal) (0) | 2023.07.08 |
spring jwt 토큰 발급하는 restapi 만들기 -2 (0) | 2023.07.05 |
spring security로 ID/PASSWORD 로그인 구현하기 (2) | 2023.06.28 |
댓글