본문 바로가기
스프링/WebClient

WebClient & WebClient vs RestTemplate

by 공부 안하고 싶은 사람 2021. 5. 20.
반응형

공통점 : HttpClient 모듈을 사용한다.

 

차이점 :

RestTemplate : WebClient 이전에 만들어졌다. 동기로만 가능하며, deprecated 될 예정

WebClient : 동기 / 비동기

 

현 시점에서 RestTemplate을 사용할 수 없는것은 아니지만, 향후 확장성을 위해 WebClient를 사용해보도록 하자.

 

 

WebClient

의존성

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

기본 WAS는 netty로 설정되지만, jetty로 설정해도 된다.

 

Instance 생성

  • Spring Boot 에선 WebClient.Builder 인터페이스가 기본 bean으로 등록
  • 전역으로 커스텀하고 싶다면, WebClientCustomizer를 Bean으로 등록하자.
private static WebClient client;

@PostConstruct
public void init() {
    client = WebClient.builder().baseUrl(IMC_BASE_URL)
        .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        //.defaultRequest()
         //.defaultCookie("쿠키키","쿠키값")
        .build();
}

 

Request

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("", "");
params.add("", "");

//1 path params
String block = client.post().uri(uriBuilder -> uriBuilder.path("/test").queryParams(params).build())
    .retrieve()
    .bodyToMono(String.class)
    .block();

//
Mono<String> hello = client.get()
    .uri(it -> it.path("/sample")
         .queryParam("name", "wonwoo")
         .build()
        ).retrieve()
    .bodyToMono(String.class);

//2 body formdata
String block = client.post().uri(uriBuilder -> uriBuilder.path("/test").build())
    .body(BodyInserters.romFormData("name", "wonwoo").with("foo","bar").with("...","..."))
    .retrieve()
    .bodyToMono(String.class)
    .block();

String block = client.post().uri(uriBuilder -> uriBuilder.path("/test").build())
    .body(BodyInserters.fromFormData(params))
    .retrieve()
    .bodyToMono(String.class)
    .block();

//3 body json
 Mono<String> hello = client.put()
            .uri("/sample")
            .body(Mono.just(new Sample("wonwoo")), Sample.class)
            .retrieve()
            .bodyToMono(String.class);

//4
EmpInfo empInfo = client.post()             // POST method
    .uri("/api/getUserInfo")    // baseUrl 이후 uri
    .body(Mono.just(new Sample("wonwoo")), Sample.class)     // set body
    .retrieve()                 // client message 전송
    .onStatus(HttpStatus -> !HttpStatus.is2xxSuccessful(), clientResponse -> Mono.error(RuntimeException::new)) // 예외처리
    .bodyToMono(EmpInfo.class)  // return body type
    .block();                   // await (sync)

//5 필터
.filter((request, next) -> next.exchange(ClientRequest.from(request) 
// ExchangeFilterFunction 구현하거나, 람다이용하여
// client호출 전에 추가작업을 할 수 있다.

 

Response

//1 상태값, 헤더와 함께
String response = req.exchange().block().bodyToMono(String.class).block();

//2 body만
String response2 = req2.retrieve().bodyToMono(String.class).block();

//3 async
Mono<String> response3 = req2.retrieve().bodyToMono(String.class);
response3.subscribe(s -> {
            System.out.println(s);
            if(stopWatch.isRunning()) // stopwatch가 실행중이면 종료
                stopWatch.stop();

            System.out.println(stopWatch.prettyPrint());
            stopWatch.start();
        });

 

참고자료 :

728x90
반응형

'스프링 > WebClient' 카테고리의 다른 글

JdbcTemplate  (0) 2021.06.04

댓글