WebClient로 외부 API 호출하기
외부 API 호출은 성공 응답뿐 아니라 연결 지연, 응답 지연, HTTP 오류도 다뤄야 한다. WebClient를 Bean으로 구성하고 단일 객체와 목록을 받아오는 예제로 설정과 호출 책임을 나눈다.
실습 준비의 기본 프로젝트에는 spring-boot-starter-webflux가 포함돼 있다. Java 17 소스 수준과 Spring Boot 3.5.16을 기준으로 한다. 아래 api.example.com은 설명용 주소이므로 자신의 API 주소로 바꾼다.
WebClient와 비동기 처리
섹션 제목: “WebClient와 비동기 처리”WebClient는 요청을 구성하고 구독 시점에 실행하는 reactive HTTP 클라이언트다. Mono<T>는 0개 또는 1개, Flux<T>는 0개 이상의 값을 전달한다. 값을 반환하는 대신 오류 신호로 끝날 수도 있다.
Spring MVC에서도 reactive 반환값을 이용해 비동기 응답을 처리할 수 있다. WebClient를 쓴다는 사실만으로 Controller의 DB 호출이나 다른 코드까지 non-blocking으로 바뀌지는 않는다.
주소와 시간 제한 설정하기
섹션 제목: “주소와 시간 제한 설정하기”partner.base-url=https://api.example.compackage com.example.tutorial;
import java.time.Duration;import io.netty.channel.ChannelOption;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.reactive.ReactorClientHttpConnector;import org.springframework.web.reactive.function.client.WebClient;import reactor.netty.http.client.HttpClient;
@Configurationpublic class PartnerClientConfiguration { @Bean public WebClient partnerWebClient(@Value("${partner.base-url}") String baseUrl) { var httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) .responseTimeout(Duration.ofSeconds(5)); return WebClient.builder() .baseUrl(baseUrl) .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); }}연결 제한 3초는 TCP 연결 수립에 대한 제한이다. 응답 제한 5초는 Reactor Netty가 응답을 읽는 동안 네트워크 읽기 사이에 허용하는 최대 간격이며, 전체 요청의 총 소요시간 상한과 다르다. DNS 조회, 연결 풀 대기, TLS handshake도 각각의 설정과 실패 원인이 있다.
HTTPS에서는 기본 인증서 검증을 유지한다. 사설 인증기관을 사용한다면 신뢰할 CA를 trust store 등에 등록한다. 인증서 검증을 전부 끄는 설정을 공통 클라이언트에 넣지 않는다. API 토큰이 필요한 경우에는 비밀값 주입 경로를 별도로 정하고 로그에 남기지 않는다.
단일 응답과 목록 받기
섹션 제목: “단일 응답과 목록 받기”다음 코드는 외부 API가 GET /profiles/{id}에서 {"id":1,"name":"Alex"} 형태의 객체를, GET /profiles에서 같은 객체의 JSON 배열을 반환한다고 가정한다.
package com.example.tutorial;
import java.time.Duration;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Service;import org.springframework.web.reactive.function.client.WebClient;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;
@Servicepublic class ProfileClient { public record Profile(long id, String name) {} private final WebClient client;
public ProfileClient(@Qualifier("partnerWebClient") WebClient client) { this.client = client; }
public Mono<Profile> find(long id) { return client.get().uri("/profiles/{id}", id).retrieve() .bodyToMono(Profile.class).timeout(Duration.ofSeconds(8)); }
public Flux<Profile> list() { return client.get().uri("/profiles").retrieve().bodyToFlux(Profile.class); }}find()의 timeout은 구독 이후 객체 수신이 끝날 때까지 8초를 허용한다. 이 제한에 걸리면 오류 신호가 발생하며 진행 중인 구독을 취소한다. list()에는 이 연산자를 붙이지 않았으며, Flux에 적용할 때는 전체 목록 시간이 아니라 각 신호 사이의 제한이 될 수 있다는 점을 구분해야 한다.
retrieve()는 기본적으로 4xx·5xx 응답을 WebClientResponseException 계열 오류로 전달한다. 실패를 빈 객체나 성공 응답으로 바꾸지 않는다. 업무상 필요한 오류 구분은 호출 계층에서 정의한다.
Controller에서 반환하기
섹션 제목: “Controller에서 반환하기”package com.example.tutorial;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;
@RestControllerpublic class ProfileController { private final ProfileClient client;
public ProfileController(ProfileClient client) { this.client = client; }
@GetMapping("/profiles/{id}") public Mono<ProfileClient.Profile> find(@PathVariable("id") long id) { return client.find(id); }
@GetMapping("/profiles") public Flux<ProfileClient.Profile> list() { return client.list(); }}Spring MVC가 반환된 publisher를 구독하고 HTTP 응답 처리를 이어간다. 이 경로에서 직접 subscribe()를 호출하거나 block()으로 기다리지 않는다. 외부 API 오류를 서비스의 어떤 HTTP 상태와 본문으로 바꿀지는 별도의 오류 응답 계약으로 정한다.
적용 기준과 한계
섹션 제목: “적용 기준과 한계”여러 외부 호출을 조합하거나 비동기 흐름을 유지할 때 WebClient를 사용할 수 있다. 단순한 동기 호출이 목적이라면 동기 HTTP 클라이언트도 비교한다. 클라이언트를 고를 때는 동시 요청 수, 연결 풀, 외부 서비스 지연과 애플리케이션의 스레드 모델을 함께 본다.
이 예제는 호출 구조를 설명하며 실제 외부 서비스, 인증과 재시도 정책은 포함하지 않는다. 성능 수치는 부하 조건과 비교 대상이 갖춰진 별도 측정으로 판단한다.