[서버][Spring] WebClient와 RestTemplate에 대해

프로그래밍/서버2021. 3. 3. 18:02

아래의 참고 링크에 스프링의 WebClient와 RestTemplate에 대해 설명이 간략하면서도 잘 되어있습니다.

 

다만 새로 작성되는 코드의 경우 RestTemplate를 대신하여 WebClient를 동기적으로 사용할 때의 코드가 없어 간단히 기록 남기려 합니다.

 

각자의 상황에 따라 인자들이나 사용하는 함수가 달라져야할 것입니다.

WebClient client = WebClient.builder()
        .baseUrl("https://kapi.kakao.com/v1/user/access_token_info")
        .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken)
        .build();

ResponseEntity<KakaoTokenResult> restExchange = client.get()
            .exchange()
            .flatMap(r -> r.toEntity(KakaoTokenResult.class))
            .block();

KakaoTokenResult kakaoTokenResult = restExchange.getBody();

여기서 핵심 부분은 block() 함수를 호출하여 동기적으로 동작하게 만드는 것입니다.

 

그리고 dependency에 직접적으로든 아니면 다른 dependency에 의해서든 spring-boot-starter-web가 포함되어 있어야 합니다.

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

 

만약 위의 라이브러리가 없다면 아래의 에러가 발생합니다.

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread

 

 

참고

madplay.github.io/post/difference-between-resttemplate-and-webclient

 

RestTemplate과 WebClient

RestTemplate 는 Deprecated 될 예정이다. WebClient 를 사용하자.

madplay.github.io

stackoverflow.com/questions/53083790/spring-webclient-as-an-alternative-to-resttemplate/53084705#comment117480100_53084705

 

Spring WebClient as an alternative to RestTemplate

The current javadoc of RestTemplate states: NOTE: As of 5.0, the non-blocking, reactive org.springframework.web.reactive.client.WebClient offers a modern alternative to the RestTemplate with eff...

stackoverflow.com

 

작성자

Posted by 드리머즈

관련 글

댓글 영역