Spring boot thread pool / spring boot 쓰레드 풀 사용 / Multi Thread ThreadPoolTaskExecutor

북마크 추가

spring에서 thread pool을  설정하여 사용하는 방법입니다.

 

1. config 파일 생성

AsyncConfig.java

 

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {

@Bean(name = "fooExecutor")
public Executor fooExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(30);
taskExecutor.setThreadNamePrefix("fooExecutor-");
taskExecutor.initialize();
return taskExecutor;
}
@Bean(name = "fooExecutor2")
public Executor fooExecutor2() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(3);
taskExecutor.setMaxPoolSize(3);
taskExecutor.setQueueCapacity(0);
taskExecutor.setThreadNamePrefix("fooExecutor2-");
taskExecutor.initialize();
return taskExecutor;
}
}


setCorePoolSize : 기본 쓰레드 사이즈

setMaxPoolSize : 최대 쓰레드 사이즈

setQueueCapacity :  Max쓰레드가 동작하는 경우 대기하는 queue 사이즈

 

fooExcutor1 의 경우 최초 5번의 요청은 CorePoolSize에 설정한 쓰레드에 할당되고 쓰레드가 끝나기 전 추가 요청이 들어오면 MaxPoolSize에 설정한 사이즈 만큼 추가로 쓰레드가 생성되어 할당됩니다.

10개의 쓰레드가 모두 돌고있는 도중 추가 요청이 들어오게 되면 QueueCapacity에서 설정한 사이즈 만큼 대기열로 들어가 처리를 기다리고, 돌고 있는 쓰레드가 종료되면 순차적으로 처리됩니다.

쓰레드와 큐가 모두 꽉차게 되면 Exception이 발생합니다. 

fooExcutor2 의 경우 3개 고정 크기로 3개의 쓰레드가 모두 처리중일때 추가 요청이 들어오면 4번째 요청부터는 Exception을 발생 시킵니다.  

 

추가로 설정하고 싶다면 bean name과 method name을 다르게 추가하면 되고

TheadNamePrefix에 사용한 이름뒤에 쓰레드 번호가 붙습니다.

 

ex) fooExcutor-1

      fooExcutor-2

      .

      .

      .

 

 

 

 

2. annotation 설정

annotation은 service에 걸어줍니다.

@Async를 사용하면 됩니다. 위의 Bean설정에서 사용한 이름을 사용합니다.

import org.springframework.scheduling.annotation.Async;

public interface FooService {

@Async("fooExecutor")
void test(
String param) throws Exception;

}

 

 

 

Controller에서

fooService.test(param);

을 호출하는 경우 멀티 쓰레드로 동작하게 됩니다.

 

 

 

 

 

 

 

 

 

 

AD
관리자
2018-03-05 16:46
SHARE