새소식

반응형
Spring

[Spring] WebClient

  • -
반응형

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

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

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

 

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);

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.