
WebClient란?
WebClient는 Spring WebFlux에서 제공하는 논블로킹(Non-blocking) HTTP 클라이언트
WebClient가 필요한 경우
외부 API 호출이 많은 서비스
결제 시스템 구현, OAuth 로그인, SMS, 알림 등등
MSA 환경
서비스간 HTTP 호출이 잦은 경우
대량 트래픽
WebClient 사용 방법
의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-webflux'
Config 설정
@Slf4j
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient() {
// 메모리 설정
ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(1024 * 1024 * 50))
.build();
// Timeout 설정
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.doOnConnected(conn -> conn
.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS))
.addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS)))
.headers(header -> header.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
);
return WebClient.builder()
.exchangeStrategies(exchangeStrategies)
.clientConnector(new ReactorClientHttpConnector(httpClient))
.filter(logRequest())
.filter(logResponse())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
// Request Log Filter
private static ExchangeFilterFunction logRequest() {
return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
log.info("Client Request : [{}, {}]", clientRequest.method(), clientRequest.url());
return Mono.just(clientRequest);
});
}
// Response Log Filter
private static ExchangeFilterFunction logResponse() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
log.info("Client Response : {}", clientResponse.statusCode());
return Mono.just(clientResponse);
});
}
}
서비스
// 토스페이먼츠 confirm 예시
Map<String, Object> body = Map.of(
"paymentKey", req.getPaymentKey(),
"orderId", req.getOrderId(),
"amount", req.getAmount()
); // body 예제
Map<String, Object> test = WebClient.builder()
.baseUrl(BASE_URL) // ex) https://api.tosspayments.com
.defaultHeaders(headers -> {
headers.setBasicAuth(secretKey, "");
headers.setContentType(MediaType.APPLICATION_JSON);
}) // 헤더 설정
.build()
.post() // method 설정
.uri(URI) // api 주소 ex)/v1/payments/confirm
.bodyValue(body) //
.retrieve()
.bodyToMono(Map.class)
.block();
이 방법을 이용하면 외부 API 호출을 통해 백엔드에서 값을 받아올 수 있다.
'Web > Spring' 카테고리의 다른 글
| [JAVA] 객체지향 프로그래밍(OOP)의 핵심 개념 (1) | 2024.04.18 |
|---|---|
| MVC 패턴이란? (0) | 2023.03.21 |
| Spring Container에 대해서 (0) | 2023.03.02 |
| Spring Framework에 대해서 (0) | 2023.03.02 |