스프링 Spring
36. Spring Boot에서 외부 API 호출 (RestTemplate vs WebClient 비교)
안녕하세요! 태마입니다.
Spring 기초 강좌입니다.
강좌의 경우
1. 주제 간단 정리
2. 상세 주제 정리
으로 이루어져 있습니다.
스프링 Spring
포스팅 시작하겠습니다 :)
1. 주제 간단 정리
1. RestTemplate이란?
✔ Spring에서 제공하는 동기(Synchronous) 기반의 HTTP 클라이언트
✔ Spring Boot 2.x까지 많이 사용되었지만, 최신 Spring Boot 3.x에서는 WebClient가 권장됨
📌 RestTemplate의 주요 특징
| 동기(Synchronous) 방식 | 요청을 보내면 응답이 올 때까지 대기 |
| 블로킹 I/O 기반 | 하나의 요청이 완료될 때까지 스레드가 블로킹됨 |
| 사용법이 간단 | 기존 REST API 호출에 익숙한 방식 |
📌 RestTemplate은 "직관적인 API 호출이 가능하지만, 동기 방식으로 인해 성능 문제가 발생할 수 있음"
2. WebClient란?
✔ Spring WebFlux에서 제공하는 비동기(Asynchronous) 기반의 HTTP 클라이언트
✔ Spring Boot 3.x에서 공식적으로 RestTemplate의 대체 기술로 권장됨
📌 WebClient의 주요 특징
| 비동기(Asynchronous) 방식 | 요청을 보낸 후, 응답을 기다리지 않고 다른 작업 수행 가능 |
| 논블로킹(Non-blocking) 방식 | 리액티브 스트림 기반으로 성능 최적화 가능 |
| 더 많은 기능 제공 | 스트리밍, 리액티브 데이터 처리 지원 |
📌 WebClient는 "비동기 및 논블로킹 기반으로 고성능 API 호출이 가능함"
3. RestTemplate vs WebClient 비교
✔ 두 방식의 차이를 비교해보자
📌 RestTemplate vs WebClient 주요 비교
| 방식 | 동기(Synchronous) | 비동기(Asynchronous) |
| I/O 처리 | 블로킹(Blocking) | 논블로킹(Non-blocking) |
| 성능 | 요청당 스레드 점유 (비효율적) | 리액티브 방식으로 처리 (고성능) |
| 실시간 데이터 스트리밍 | 지원하지 않음 | Flux 기반 실시간 데이터 스트리밍 가능 |
| Spring 지원 | Spring Boot 2.x까지 사용 가능 | Spring Boot 3.x에서 권장 |
📌 Spring Boot 3.x에서는 "WebClient 사용이 권장되며, RestTemplate는 레거시 코드에서 유지보수용으로만 사용"
✅ 여기까지 RestTemplate과 WebClient의 개념과 차이점을 배웠습니다!
👉 "그렇다면, Spring Boot에서 실제로 RestTemplate과 WebClient를 어떻게 사용할까?"
✅ 2부에서 RestTemplate과 WebClient의 실제 사용법과 예제를 배워봅시다!
2. 상세 주제 정리
1. RestTemplate을 활용한 API 호출
✔ RestTemplate을 사용하여 외부 API를 호출하는 방법
📌 1️⃣ RestTemplate Bean 등록 (AppConfig.java)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
✔ RestTemplate은 @Bean으로 등록하여 사용하는 것이 일반적
📌 2️⃣ RestTemplate을 활용한 GET 요청 (ApiService.java)
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getDataFromApi() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
return restTemplate.getForObject(url, String.class);
}
}
✔ getForObject() 메서드를 사용하여 외부 API 데이터를 가져옴
📌 3️⃣ 컨트롤러에서 API 호출 (ApiController.java)
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class ApiController {
private final ApiService apiService;
public ApiController(ApiService apiService) {
this.apiService = apiService;
}
@GetMapping("/fetch")
public String fetchData() {
return apiService.getDataFromApi();
}
}
✔ /api/fetch 엔드포인트를 호출하면 외부 API 데이터를 반환
📌 RestTemplate을 활용하면 "간단한 REST API 호출을 쉽게 구현 가능"
2. WebClient를 활용한 API 호출
✔ WebClient를 사용하여 비동기 방식으로 API를 호출하는 방법
📌 1️⃣ WebClient Bean 등록 (AppConfig.java)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class AppConfig {
@Bean
public WebClient webClient() {
return WebClient.builder().baseUrl("https://jsonplaceholder.typicode.com").build();
}
}
✔ WebClient는 baseUrl을 설정하여 API 호출을 쉽게 구성 가능
📌 2️⃣ WebClient를 활용한 GET 요청 (ApiService.java)
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class ApiService {
private final WebClient webClient;
public ApiService(WebClient webClient) {
this.webClient = webClient;
}
public Mono<String> getDataFromApi() {
return webClient.get()
.uri("/posts/1")
.retrieve()
.bodyToMono(String.class);
}
}
✔ WebClient는 Mono<>를 반환하여 비동기 방식으로 API 데이터를 가져옴
📌 3️⃣ 컨트롤러에서 API 호출 (ApiController.java)
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/api")
public class ApiController {
private final ApiService apiService;
public ApiController(ApiService apiService) {
this.apiService = apiService;
}
@GetMapping("/fetch")
public Mono<String> fetchData() {
return apiService.getDataFromApi();
}
}
✔ /api/fetch 엔드포인트를 호출하면 비동기 방식으로 데이터를 가져옴
📌 WebClient를 활용하면 "비동기 방식으로 높은 성능을 유지하며 API 데이터를 가져올 수 있음"
✅ 여기까지 Spring Boot에서 외부 API를 호출하는 방법을 배웠습니다!
👉 "그렇다면, Spring Boot에서 멀티 모듈(Multi-Module) 프로젝트를 어떻게 설계할까?"
✅ 다음 회차에서 Spring Boot에서 멀티 모듈(Multi-Module) 프로젝트 설계 방법을 배워봅시다!
'IT Developer > Spring' 카테고리의 다른 글
| Spring 기초 <40. 실전 프로젝트에서 Spring Boot 적용 Best Practices> (0) | 2025.04.25 |
|---|---|
| Spring 기초 <39. Spring Boot에서 서버 성능 튜닝 및 최적화 방법> (0) | 2025.04.24 |
| Spring 기초 <38. Spring Boot에서 CQRS 패턴 적용 및 활용법> (0) | 2025.04.23 |
| Spring 기초 <37. Spring Boot에서 멀티 모듈(Multi-Module) 프로젝트 설계> (0) | 2025.04.22 |
| Spring 기초 <35. Spring에서 커스텀 애너테이션(Custom Annotation) 만들기> (1) | 2025.04.20 |
| Spring 기초 <34. Spring Boot 실무 Best Practices 및 최신 트렌드 (Reactive Programming, Cloud Native)> (1) | 2025.04.19 |
| Spring 기초 <33. Spring Boot에서 A/B 테스트와 Feature Toggle 적용> (0) | 2025.04.18 |
| Spring 기초 <32. Spring Boot에서 OpenTelemetry를 활용한 애플리케이션 모니터링> (0) | 2025.04.17 |