Spring/Framework

spring boot 3.2 - restclient & declarative http interface

바람을타고2 2023. 12. 3. 09:19

github demo : https://github.com/gwagdalf/declarative-http-interface-demo

 

declarative HTTP interface 란

Spring 6.0 과 Spring boot 3 에서 declarative HTTP interface 가 추가되었습니다

https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-http-interface

 

openFeign 과 유사하게, interface 만 정의하고 http client 를 사용할 수 있게 된건데요. 

public interface WebClientDeclarativeInterface {

	@GetExchange("/v6/latest/KRW")
	Map getRate();
}

 

아직은 몇 줄정도의 configuration code 도 추가해야 합니다

이 configuration code 에서 restTemplate 을 사용할지 아니면,  WebClient 또는 spring boot 3.2 에서 추가된 RestClient 를 사용할 지 설정할 수 있습니다.

https://github.com/gwagdalf/declarative-http-interface-demo/blob/main/src/main/java/com/example/declarativehttpinterface/demo/client/config/DeclarativeHttpInterfaceClientConfig.java

 

 

출시 배경

아래 유튜브에서 출시 배경이 소개되고 있는데요.

  • OpenFeign 측과 협업과정에서 다소 지연이 발생했고
  • non-blocking 을 지원

하기 위해서 라고 소개되고 있습니다만,  제 소견으로는 좋은 기능이니 Spring 에서도 지원하고 싶은게 아니였나 싶습니다.

 

출처 : https://youtu.be/3NcmlrumSOc?t=813

 

 

 

Http client history

아래는 각각의 http client 가 출시된 버전입니다. 

type Spring Boot Version Spring Version
Rest Template                         1.5                 4.3
WebClient                         2.0                 5.0
RestClient                         3.2                 6.1

 

RestTemplate 은 가장 오래된 http client 입니다만, 너무 오래되어 유지보수하기 힘들어, Spring 쪽에서 Retire 싶어하고 한다는 느낌을 받았습니다.

 

WebClient 는 동기와 비동기를 모두 지원하며, 함수형으로 사용할 수 있는 훌륭한 component 이지만,

 webflux dependency 를 추가해야 된다는 점이 일부 유저들에게 불만으로 제기된 것 같습니다.

 

그래서 WebClient 와 매우 유사하지만, webflux 에 의존하지 않는 spring-web 만 있으면 사용가능한,

동기에 특화된 RestClient 가 spring boot 3.2 에서 출시된 것 같습니다.

 

demo 

아래 데모에서는 

  • RestTemplate + declarative
  • WebClient + declarative
  • RestClient + declarative
  • openFeignClient

위 4개를 각각 비교할 수 있는 코드를 작성하였습니다. 

 

demo code 보면 확인 할 수 있습니다.

https://github.com/gwagdalf/declarative-http-interface-demo

 

GitHub - gwagdalf/declarative-http-interface-demo

Contribute to gwagdalf/declarative-http-interface-demo development by creating an account on GitHub.

github.com

 

 

 

Reference

official : https://docs.spring.io/spring-framework/reference/integration/rest-clients.html

토비 이일민님 :  https://www.youtube.com/watch?v=Kb37Q5GCyZs

reference 모음 : https://ride-wind.tistory.com/91