티스토리 뷰
RestTemplate WebClient, 어느 경우에 성능차이가 날까?
KimDoubleB 2022. 3. 15. 01:10WebClient
를 사용하되, block
을 사용한다? 이게 RestTemplate
같은 Blocking 기반의 http client를 사용하는 것과 무엇이 다를까?
사실 단일으로 하나의 request를 다루는 것이라면 성능이 거의 같을 것이다. 어느정도 각 http client 구현도에 차이가 있을 수 있지만, 유의미한 차이가 있지는 않을 것이다.
- 아래는 아주 대충 작성해 본 예시
// WebClient
var webclientResponse = WebClient.create("some-url").get().retrieve().bodyToMono(String.class);
webclientResponse.block();
// RestTemplate
var restTemplateResponse = new RestTemplate().exchange("some-url", HttpMethod.GET, null, String.class);
하지만 비동기 시퀀스에서 여러 요청을 처리할 때는 WebClient을 사용해 더 좋은 성능을 이끌어 낼 수 있다.
var baseUrl = "some-url";
var payloads = List.of("some-data1", "some-data2", "some-data3");
var webClientResponse = Flux.fromIterable(payloads)
.flatMap(payload -> WebClient.create(baseUrl)
.post()
.bodyValue(payload)
.retrieve()
.bodyToMono(String.class))
.collectList()
.block();
var restTemplateResponse = Flux.fromIterable(payloads)
.map(payload -> new RestTemplate().exchange(baseUrl,
HttpMethod.POST,
new HttpEntity<>(payload),
String.class))
.map(HttpEntity::getBody)
.collectList()
.block();
반환되는 결과는 같다. 하지만 WebClient는 비동기적으로 동작하기에 페이로드가 넘어와 요청을 수행하게 될 때 pending 되지 않는다. 즉, 바로 다음으로 넘겨버린다 (여기서는 flatMap
으로 시퀀스 변경이 일어난다). 그러다보니 netty thread(nio) 1/2/3이 거의 동시에 동작하게 되고, collectList
에 다다랐을 때 맨 마지막의 netty thread로 합쳐져 block이 실행된다.
RestTemplate의 경우는 다른데, request를 날릴 때마다 pending 된다. 즉, 응답을 기다리며 결과가 올 때까지 기다리게 된다. 그러면서 순차적으로 동작하게 되고, 예제에서는 3개의 요청이므로 결과 시간이 3개의 딜레이가 다 합쳐진 시간만큼 늦어지게 된다.
자세한 코드 내용은 아래 주소를 참조부탁드립니다.
GitHub - KimDoubleB/spring-learning: 🌱 스프링 탐험과 성장 •̀.̫•́✧
🌱 스프링 탐험과 성장 •̀.̫•́✧ . Contribute to KimDoubleB/spring-learning development by creating an account on GitHub.
github.com
'Development > Java, Kotlin, Frameworks' 카테고리의 다른 글
Java Memory 이해 & OOME 오류에 관하여 (0) | 2022.04.27 |
---|---|
Flame graph (Profiling) (0) | 2022.04.27 |
Reactor just, defer, fromCallable 에 대하여 (3) | 2022.03.15 |
JUnit5 Tag & Filtering (2) | 2022.02.17 |
Kubernetes에서의 Spring boot Profile 설정 (0) | 2022.01.18 |
- Total
- Today
- Yesterday
- MySQL
- OpenTelemetry
- 일상
- java
- 비동기
- Kubernetes
- container
- HTTP
- 백준
- docker
- 하루
- Log
- k8s
- python
- WebFlux
- gradle
- boj
- 쿠버네티스
- 로그
- 알고리즘
- Spring boot
- tag
- Algorithm
- Clean Architecture
- jasync
- Spring
- Intellij
- Istio
- c++
- 클린 아키텍처
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |