본문 바로가기
Spring

[Spring] RestTemplate vs WebClient 어떤 걸 써야 할까?

by 노력남자 2023. 2. 14.
반응형

문득 WebClient를 쓰다가 왜 RestTemplate을 안 쓰게 됐지? 라는 생각에 이유를 찾아봤다.

 

spring 5 나올시기에 RestTemplate가 없어진다 뭐한다라는 루머가 많이 돌았는데 어떻게 된건지 알아보자.

 

RestTemplate

 

RestTemplate는 Spring 3.0 버전에 나온 Synchronous 클라이언트로 http 요청을 처리하기 위한 모듈이다.

 

 

RestTemplate (Spring Framework 6.0.4 API)

postForLocation Create a new resource by POSTing the given object to the URI template, and returns the value of the Location header. This header typically indicates where the new resource is stored. URI Template variables are expanded using the given URI v

docs.spring.io

 

위 spring docs에 있는 NOTE 부분에 내 질문에 답이 있다.

 

NOTE:
 As of 5.0 this class is in maintenance mode, with only minor requests for changes and bugs to be accepted going forward. Please, consider using the 
org.springframework.web.reactive.client.WebClient
 which has a more modern API and supports sync, async, and streaming scenarios.

 

spring 5부터 유지 모드(maintenance mode)가 되었다고 한다. 언제인지는 모르겠지만 유지하다가 버전 업그레이드 하면서 사라질 위험이 있다는 말이다.

 

두 번째 문장을 보면 많은 modern API를 가지고 있고 동기, 비동기, 스트리밍 시나리오까지 가능한 WebClient를 쓰라고 추천한다. please...

 

WebClient

 

WebClient는 Spring 5.0부터 나온 RestTemplate 상위 호환 모듈이다.

 

Non-blocking, reactive 클라이언트로 http 요청을 처리하기 위함이다.

 

WebFlux에 있는 모듈이라 org.springframework:spring-webflux 의존성을 추가해줘야 사용할 수 있다.

 

 

WebClient (Spring Framework 6.0.4 API)

post Start building an HTTP POST request. Returns: a spec for specifying the target URL

docs.spring.io

 

RestTemplate을 사용하다가 WebClient를 사용하려면 reactor에 대한 공부를 좀 해야한다.

 

Mono, Flux가 나오고 로직 작성 방법이 다르기 때문이다.

 

메소드들이 알아보기 쉽게 잘 작성되어 있으니 RestTemplate보다 사용하기가 훨씬 편하다.

 

결론

 

RestTemplate은 spring 6에서도 maintenance mode로 계속 유지 중이기 때문에 굳이 webclient로 강제로 마이그레이션할 필요가 없어보인다.

 

Deprecated된다고 얘기가 나오면 그때 준비해도 무방할 거 같다.

반응형

댓글