Spring/etc

[Spring] WebClient

joo_k 2024. 6. 2. 23:18
반응형

Spring Application에서 다른 API를 호출하기 위해서는 HTTP Client 호출이 필요하다. 

다양한 library를 통해서 해당 기능을 사용할 수 있는데

그중에 하나인 Spring WebClient에 대해서 알아보자. 

-> org.springframework : spring-webflux.jar 

 

WebClient

  • HTTP Request를 수행하는 Client
  • Nonblocking I/O
  • Reactive Streams back pressure
  • High concurrency with fewer hardware resources
  • Functional-style, fluent API that takes advantage of Java 8 lambdas
  • Synchronous and asynchronous interactions
  • Streaming up to or streaming down from a server 

WebClient 생성

  • WebClient.create()
  • WebClient.create(String baseUrl)
  • WebClient.builder()....build()

WebClient.builder()를 사용하면 다양한 옵션 설정이 가능하다. 

 

MaxInMemorySize

데이터 전송 시 buffer memory제한 존재 ( 디폴트 : 256KB )

WebClient webClient = WebClient.builder()
		.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
		.build();

 

Client Connector

WebClient webClient = WebClient.builder()
		.clientConnector(new ReactorClientHttpConnector(httpClient))
		.build();

 

retrieve()

repsonse body를 받아 디코딩하는 메서드

 

ResponseEntity로 받는 기본적인 형태

WebClient client = WebClient.create("https://example.org");

Mono<ResponseEntity<Person>> result = client.get()
		.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
		.retrieve()
		.toEntity(Person.class);

 

ResponseEntity의 body만 받는 형태 

WebClient client = WebClient.create("https://example.org");

Mono<Person> result = client.get()
		.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
		.retrieve()
		.bodyToMono(Person.class);

 

exchangeToMono()

retrieve() 메서드의 대안으로, ClientResponse에 직접 접근할 수 있어 더 많은 제어권을 제공

예를 들어 HTTP 응답 상태에 따라 응답을 다르게 처리하고자 할 때 유용

Mono<Person> entityMono = client.get()
    .uri("/persons/1")
    .accept(MediaType.APPLICATION_JSON)
    .exchangeToMono(response -> {
        if (response.statusCode().equals(HttpStatus.OK)) {
            return response.bodyToMono(Person.class);
        }
        else {
            return response.createException().flatMap(Mono::error);
        }
    });
반응형