Spring6.1新特性,四种方式调用REST接口(RestClient、WebClient、RestTemplate、HTTP Interface)

2024-06-04 1548阅读

个人博客:无奈何杨(wnhyang)

个人语雀:wnhyang

共享语雀:在线知识共享

Github:wnhyang - Overview


官网

REST Clients :: Spring Framework

The Spring Framework provides the following choices for making calls to REST endpoints:

  • RestClient - synchronous client with a fluent API.
  • WebClient - non-blocking, reactive client with fluent API.
  • RestTemplate - synchronous client with template method API.
  • HTTP Interface - annotated interface with generated, dynamic proxy implementation.

    RestClient

    官方描述:RestClient是一个同步HTTP客户端,它提供了一个现代、流畅的API。它提供了对HTTP库的抽象,允许从Java对象到HTTP请求的方便转换,以及从HTTP响应创建对象。

    Spring6.1版本新特性。

    创建

    创建RestClient非常简单,可以使用静态create方法,也可以使用builder创建,其提供了非常丰富的定制化选项,请求工厂、消息转换器、拦截器、默认头、请求初始化器等等,简单易懂。

    RestClient defaultClient = RestClient.create();
    RestClient customClient = RestClient.builder()
      .requestFactory(new HttpComponentsClientHttpRequestFactory())
      .messageConverters(converters -> converters.add(new MyCustomMessageConverter()))
      .baseUrl("https://example.com")
      .defaultUriVariables(Map.of("variable", "foo"))
      .defaultHeader("My-Header", "Foo")
      .requestInterceptor(myCustomInterceptor)
      .requestInitializer(myCustomInitializer)
      .build();
    

    使用

    使用RestClient更为简单,请求URL、Header、Body、相应Response接受、异常处理等等相当丰富简单。

    String result = customClient.get()
            .uri("https://example.com/this-url-does-not-exist")
            .retrieve()
            .onStatus((code) -> code.value() / 100 == 4, (request, response) -> {
                throw new RuntimeException(response.getStatusCode() + " " + response.getHeaders());
            })
            .body(String.class);
    

    WebClient

    WebClient是一个无阻塞、响应式的客户端,用于执行HTTP请求。它在5.0中引入,提供了RestTemplate的替代方案,支持同步、异步和流式传输场景。

    早在Spring5版本中就已经出现,创建方法和RestClient差不多,简单示例如下,其他详细内容可参考官网可Java Doc。

    WebClient webClient = WebClient.builder().baseUrl("http://localhost:8081").build();
    

    RestTemplate

    Spring6.1新特性,四种方式调用REST接口(RestClient、WebClient、RestTemplate、HTTP Interface) 第1张

    相比于上面两位这个更是古老,也正因此更为常见,使用的更多。但是官网明确表示,推荐使用RestClient替换RestTemplate,甚至还细心的整理了替换方案,可知官方可能计划着在未来彻底废弃RestTemplate,也许哦。

    Spring6.1新特性,四种方式调用REST接口(RestClient、WebClient、RestTemplate、HTTP Interface) 第2张

    HTTP Interface

    官方描述:Spring Framework允许您使用@HttpExchange方法将HTTP服务定义为Java接口。您可以将这样的接口传递给HttpServiceProxyFactory,以创建一个代理,该代理通过HTTP客户端(如RestClient或WebClient)执行请求。您还可以从@Controller实现用于服务器请求处理的接口。

    简单的来讲,可以类比为OpenFeign,使用方法是几乎一样的。

    Spring6.1新特性,四种方式调用REST接口(RestClient、WebClient、RestTemplate、HTTP Interface) 第3张

    这个也是Spring6的特性,最开始官方支持了WebFlux的实现,后来才加入的RestClient和RestTemplate,使用方式如上图。

    方法级别的注解有下,是不是和使用OpenFeign时几乎一样了,其实不然,@RequestHeader、@RequestBody、@PathVariable、@RequestParam、@CookieValue等等也是支持的。

    @GetExchange
    @PostExchange
    @PutExchange
    @DeleteExchange
    @PatchExchange
    

    小结

    可以说在Spring6.1之后再进行REST调用就有更加丰富的选择了,而且更加简单方便。

    写在最后

    拙作艰辛,字句心血,望诸君垂青,多予支持,不胜感激。


    个人博客:无奈何杨(wnhyang)

    个人语雀:wnhyang

    共享语雀:在线知识共享

    Github:wnhyang - Overview

    Spring6.1新特性,四种方式调用REST接口(RestClient、WebClient、RestTemplate、HTTP Interface) 第4张


    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]