Programming/Spring Boot 시작하기
TaskExecutor 로 @Async 의 Thread 을 Pool 로 관리하기
zepinos
2019. 1. 22. 11:24
반응형
Spring 에서 @Async 을 이용해서 쉽게 비동기 method 을 만들 수 있습니다.
대략 다음과 같이 method 정의를 먼저 할 수 있을 겁니다.
@Async public CompletableFuture<String> async(String param1, int param2) { return CompletableFuture.completedFuture(param1 + " : " + param2); }
그리고 이를 다음과 같이 사용할 수 있겠죠.
CompletableFuture<String> result = service.async("status", 100);
하지만, 이렇게 그냥 사용할 경우 @Async 는 SimpleAsyncTaskExecutor 을 기본 TaskExcutor 로 이용하기 때문에 async method 을 호출할 때마다 새로운 Thread 을 생성하게 됩니다. 반드시 문제가 발생한다고 할 수는 없지만, 새로운 Thread 을 생성하고 소멸하는 비용이 증가하고 많은 요청이 몰릴 경우 시스템 장애로 이어질 수 있기 때문에 Pool 을 써야할 때가 있습니다.
Spring Boot 에서 Java Config 을 이용해서 쉽게 이를 해결할 수 있는데 아래와 같이 ThreadPoolTaskExecutor 을 이용하도록 해주면 됩니다.
@Configuration @EnableAsync public class ExecutorConfig { @Bean(name = "taskExecutor") public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(3); taskExecutor.setMaxPoolSize(30); taskExecutor.setQueueCapacity(10); taskExecutor.setThreadNamePrefix("task-pool-"); taskExecutor.initialize(); return taskExecutor; } }
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor 을 새롭게 생성해서 pool 의 크기와 Thread 명의 접두사 등을 선언해줄 수 있습니다. 그리고 @Bean 으로 등록할 때 name 을 지정할 수 있는데, 이런 식으로 복수의 TaskExecutor 을 등록한 뒤 @Async 에서 원하는 TaskExecutor 을 선택해서 사용할 수도 있습니다.
반응형