카카오 소셜 로그인을 구현하며 토큰을 응답받아오는 과정에서 RestTemplate 이 deprecated 되었다고해서 WebClient 를 사용했었는데 오해와 각 방식의 차이점을 정리해보려한다.
우선, RestTemplate 에 대한 오해를 먼저 풀어보자.
RestTemplate 은 Deprecated 되었는가?
결론부터 얘기하자면 그렇지 않다.
RestTemplate 과 WebClient 의 차이점을 정리하기위해 찾아보다 알게된 내용으로, 직접 찾아보지않은 모든 것을 의심해야겠구나 하는 깨달음을 준 사례였다. 관련 내용은 토비 님이 올려주신 youtube 영상이 정말 정리가 잘 되어있었다.
우선 spring-web 6.0.13 기준으로 RestTemplate 문서를 확인해보아도 deprecated 되었다는 말은 찾아볼 수 없다.
Spring Framework 5.0 부터 유지보수 모드로 들어가며 WebClient 를 권장한다는 말 정도이다.
( 최신 6.1.1 API 에서도 특이 사항은 없었다. )

그렇다면 왜 deprecated 되었다는 말이 떠돌았을까?
과거 히스토리 내역을 통해 공식 문서에서 deprecated 되었다는 내용이 있었다는 것을 알 수 있었다. 현재는 수정된 상태인 것이다.

요약하자면 RestTemplate 은 depreacated 되지 않았고 Spring 은 WebClient 사용을 권장한다는 것이다.
RestTemplate 과 WebClient
RestTemplate 과 WebClient 는 Spring Framework 에서 HTTP 요청을 처리하는 두 가지 방법이다.
1. RestTemplate
- Spring Framework 3.0 부터 사용
- 동기식 ( 한 번에 하나의 HTTP 요청만 처리하고 해당 요청이 완료될 때까지 대기 )
- Blocking I/O ( 요청이 처리되는 동안 현재 스레드가 차단 -> 대규모 트래픽 처리에 제한적일 수 있음 )
- 사용하기 쉬운 API 제공
- spring-web 모듈에 포함되어 있다.
- 동시성 처리에 적합하지 않다.
2. WebClient
- Spring Framework 5 및 Spring WebFlux 와 함께 도입
- 비동기 및 리액티브 프로그래밍 지원
- Non-Blocking I/O ( 요청을 처리하는 동안 스레드가 차단되지 않음 )
- RestTemplate 에 비해 러닝커브가 높다.
- webflux 모듈을 추가해야 한다.
implementation 'org.springframework.boot:spring-boot-starter-webflux'
3. 실습
간단한 실습을 통해 사용 방법을 정리해보자. ( 단순한 POST 요청을 통해 응답 값 출력 )
- RestClientConfig 를 생성하여 RestTemplate 과 WebClient Bean 으로 등록하기.
@Component
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public WebClient webClient() {
return WebClient.builder().build();
}
}
- Controller 에서 각 요청을 통해 받은 응답 값 출력하기.
( requestUrl 에 해당하는 localhost:8081/user 에는 회원 정보를 저장하고 응답하는 API 를 구현해두었다. )
@RestController
@RequiredArgsConstructor
public class RestClientController {
private final RestTemplate restTemplate;
private final WebClient webClient;
String requestUrl = "http://localhost:8081/user";
/*1. RestTemplate 사용 */
@GetMapping("/rest-template")
public ResponseEntity<?> useRestTemplate() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 바디에 담을 데이터 설정
Map<String, Object> map = new HashMap<>();
map.put("email", "test@test.com");
map.put("nickname", "test1234");
map.put("categories", Arrays.asList("취미", "드로잉"));
// HTTP 요청 보내기
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headers);
String response = restTemplate.postForObject(requestUrl, entity, String.class);
return ResponseEntity.ok().body(response);
}
/*2. WebClient 사용 */
@GetMapping("/web-client")
public ResponseEntity<?> useWebClient() {
// 바디에 담을 데이터 설정
Map<String, Object> map = new HashMap<>();
map.put("email", "test@test.com");
map.put("nickname", "test1234");
map.put("categories", Arrays.asList("취미", "드로잉"));
// HTTP 요청 보내기
String response = webClient.post()
.uri(requestUrl)
.bodyValue(map)
.retrieve()
.bodyToMono(String.class)
.block();
return ResponseEntity.ok().body(response);
}
}
- 실행 결과

정리
비동기식 처리에는 WebClient 를 사용하는 것이 맞지만 전통적인 애플리케이션에서 WebClient 가 더 적합하냐고 하면 그것은 또 아니다. 각 애플리케이션마다 적합한 방법을 선택하여 사용하면 될 것 같다. 지금 생각해보면 소셜 로그인에 굳이 webflux 모듈을 추가하면서까지 WebClient 를 고집할 이유는 없었던 것 같다.
참고
https://www.baeldung.com/spring-webclient-resttemplate
'Web' 카테고리의 다른 글
| [Spring] 예외 코드 Enum 으로 관리하기 (0) | 2023.12.17 |
|---|---|
| [Spring] actuator 를 통한 shutdown endpoint 생성 (0) | 2023.12.10 |
| [Spring] Swagger 에 JWT 설정하기 (0) | 2023.11.26 |
| [Spring] Spring 3.x + Swagger 설정 (0) | 2023.11.19 |
| [System Design] URL 단축기 설계 -1 (0) | 2023.11.05 |