RestTemplate와 WebClient
RestTemplate
정의
- org.springframework.web.client.RestTemplate
- Spring 프레임워크에서 제공하는 HTTP 통신을 간편하게 처리할 수 있는 동기적인 클라이언트
- REST API를 위한 다양한 메서드를 제공하여 개발자가 HTTP 요청을 손쉽게 보내고 응답을 처리할 수 있도록 지원
- Spring Boot에 기본 탑재되어 있어서 별도 import 필요 X
특징
- 멀티 스레드
- Blocking I/O
주요 메소드
- getForObject() = HTTP GET + 결과값 Object로 반환
- getForEntity() = HTTP GET + 결과값 ResponseEntity로 반환
- postForLocation() = HTTP POST + 결과값으로 헤더에 저장된 URI 반환
- postForObject() = HTTP POST + 결과값 Object로 반환
- postForEntity() = HTTP POST + 결과값 ResponseEntity로 반환
- delete() = HTTP DELETE
- put() = HTTP PUT
기본 세팅
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
WebClient
정의
- org.springframework.web.reactive.function.client.WebClient
- Spring WebFlux 프레임워크에서 제공하는 비동기적인 HTTP 클라이언트
implementation 'org.springframework.boot:spring-boot-starter-webflux'
특징
- 리액티브 스트림 기반
- Publisher-Subscriber 모델을 사용하여 데이터를 처리
- 싱글 스레드
- Non-Blocking I/O
- 비동기적 HTTP 요청 처리
주요 메소드
- create() = WebClient 객체 생성
- builder() = WebClient Builder 객체 생성
- get() = HTTP GET
- post() = HTTP POST
- put() = HTTP PUT
- delete() = HTTP DELETE
- retrieve() = HTTP 요청 전송 (간단한 요청 및 응답 처리)
- exchange() = HTTP 요청 전송 (복잡한 요청 및 응답 처리 - ClientResponse)
- block() = 참조한 명령 동기 처리
ClientResponse
- Spring WebFlux의 WebClient로부터 반환되는 HTTP 응답을 표현하는 클래스
- status() = HTTP 상태 조회 (숫자 + 메시지)
- statusCode() = HTTP 상태 코드 조회 (숫자만)
- header() = HTTP 헤더 조회
- bodyToMono() = HTTP 바디 -> Mono 변환
- bodyToFlux() = HTTP 바디 -> Flux 변환
Mono & Flux
- Mono, Flux 둘 다 Spring WebFlux 프레임워크에서 사용되는 리액티브 스트림(일종의 비동기 스트림)의 구현체 → 비동기적인 데이터 스트림을 처리하는 데 사용
- Mono = 0개 또는 1개의 요소를 가진 단일 값을 발행하는 스트림
- Flux = 0개 이상의 요소를 가진 여러 값을 발행하는 스트림
- doOnTerminate() = 비동기 작업이 모두 완료되었을 때의 로직 처리 (subscribe의 세번째 파라미터와 같은 역할)
기본 세팅
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class WebClientExample {
public static void main(String[] args) {
// 지정한 IP로 WebClient 객체 생성 (Builder.ver)
WebClient webClient = WebClient.builder() // WebClient.Builder를 사용하여 WebClient 객체 생성
.baseUrl("https://api.example.com") // 기본 URL 설정
.build(); // WebClient 객체 생성
// 지정한 IP로 WebClient 객체 생성 (create.ver)
WebClient webClient = WebClient.create("https://api.example.com");
int result = webClient.get().uri("/resource")
.retrieve()
.bodyToMono(Integer.class)
.block(); // 응답을 동기 처리
Mono<String> responseBodyMono = webClient.get() // HTTP GET
.uri("/resource") // 나머지 uri
.retrieve() // 요청 전송
.bodyToMono(String.class); // 응답(String)을 받아 Mono로 변환
Mono<String> postResponse = webClient.post()
.uri("/resource")
.bodyValue(new DataObject("value1", "value2")) // Request body
.retrieve()
.bodyToMono(String.class);
Mono<String> putResponse = webClient.put()
.uri("/resource/{id}", 1)
.bodyValue(new DataObject("newValue1", "newValue2")) // Request body
.retrieve()
.bodyToMono(String.class);
Mono<Void> deleteResponse = webClient.delete()
.uri("/resource/{id}", 1)
.retrieve()
.bodyToMono(Void.class);
// Mono 객체를 구독하여 응답 객체 및 오류 비동기 처리
responseBodyMono.subscribe(
res -> System.out.println("Response Body: " + res),
err -> System.err.println("Error: " + err),
() -> System.out.println("Request Completed")
);
}
}
- WebClient.create(ip) = 지정한 IP에 대한 WebClient 객체 생성
- block() = 동기 처리
- subscribe() = 참조한 Mono, Flux 객체에 대한 응답 본문 및 에러를 비동기 처리 가능
- 인자명은 마음대로 설정 가능
- 첫번째 파라미터는 responseBody, 두번째 파라미터는 error, 세번째 파라미터는 비동기 작업이 모두 완료되었을 때의 로직을 정의
- 첫번째 파라미터만 필수고 나머지는 Optional
- 세번째 파라미터는 보통 Runnable 호출을 위해 ()를 입력
※ webClient.bodyToMono 혹은 webClient.bodyToFlux를 통해 Mono나 Flux를 반환하는 로직을 구성해도 해당 Mono, Flux 객체를 처리하는 로직이 정의되지 않으면 정해놓은 URL에 호출이 되지 않음