허원철의 개발 블로그

Spring Boot - Async 제대로 사용하기 본문

web

Spring Boot - Async 제대로 사용하기

허원철 2017. 5. 18. 15:09
이번 글은 Spring Boot에서 Async를 제대로 사용해보기 위한 글입니다.
 
스프링캠프를 다녀온 이후에 Spring에서 제공해주는 Async를 다시 한번 되짚어보고자 SimpleAsyncTaskExecutor와 다른 스레드풀을 비교하여 포스팅해보기로 하였습니다.
 
SimpleAsyncTaskExecutor는 스레드풀이 아닙니다. 그렇기 때문에 스레드를 관리하고 재사용하는 것이 아니라 계속 만들어냅니다. 스레드는 자원이 많이 들기 때문에 SimpleAsyncTaskExecutor를 쓰지 말아야합니다.
 
SimpleAsyncTaskExecutor와 쓰레드풀을 만들어서 visualvm으로 가시화 해보겠습니다.
 
 
1. Bean 등록
 
①  SimpleAsyncTaskExecutor
 
1
2
3
4
@Override
public Executor getAsyncExecutor() {
    return new SimpleAsyncTaskExecutor("heowc-async-");
}
cs
 
② Custom Thread Pool
 
1
2
3
4
5
6
7
8
9
10
@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(10);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("heowc-async-");
    executor.initialize();
    return executor;
}
cs
 
 
2. HTTP Test
 
- async를 10번 호출해보고 visualvm 확인한 결과입니다.
 
①  SimpleAsyncTaskExecutor
 

 
② Custom Thread Pool
 



3. 결과


- thread를 매번 생성하는 SimpleAsyncTaskExecutor에 비해 custom thread pool에서는 core 갯수 만큼인 thread가 2개만 생성된 것을 확인할 수 있습니다.

 

 

4. AsyncRestTemplate 사용하기

 

- RestTemplate를 비동기로 활용하기 위한 방법입니다.

- 기본적으로는 Async와 비슷하게 쓰레드를 계속 생성하는 SimpleAsyncTaskExecutor(BIO)라는 것을 사용합니다. AsyncRestTemplate를 제대로 사용하기 위해서는 NIO 라이브러리를 추가해줘야 합니다.


 4-1. Gradle 설정

 

- NIO 라이브러리에는 Apache와 Netty에서 제공하는 것이 있습니다.

 

1
2
3
4
5
dependencies {
    compile('org.apache.httpcomponents:httpasyncclient:4.1.3')
    compile('io.netty:netty-all:4.1.11.Final')
// ...
}
cs

 

 4-2. Bean 설정

 

- Apache에서 제공해주는 것은 HttpCoponentsAsyncClientHttpRequestFactory를 사용하면 되고, Netty에서 제공해주는 것은 Netty4ClientHttpRequestFactory를 이용하면 됩니다.

 

1
2
3
4
5
@Bean
    public AsyncRestTemplate getAsyncRestTemplate() {
//        return new AsyncRestTemplate(new Netty4ClientHttpRequestFactory());
        return new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory());
    }
cs

 

 4-3. HTTP Test

 

  

'web' 카테고리의 다른 글

책 '토비의 스프링 3.1' 후기  (405) 2017.09.12
Spring Boot - CORS  (410) 2017.06.25
Spring Boot - Excel Upload & Download  (418) 2017.05.05
Spring Boot - Data JPA & ModelMapper  (414) 2017.04.30
Spring Boot - MyBatis  (396) 2017.04.13
Comments