Spring 5 WebClient 详细使用教程
1. 概述
在本文中,我们将研究WebClient,它是Spring5中引入的响应式web客户端类库,最大特点是支持异步调用;我们还将学习WebTestClient,用于单元测试。
简单地说,WebClient是一个接口,执行web请求的主要入口点。
它是Spring Web Reactive模块的一部分,并且取代经典的RestTemplate而生。此外,新的客户端是一个响应式的、非阻塞的技术方案,可以在HTTP/1.1协议上工作。
该接口有一个实现,即DefaultWebClient类。
2. WebClient 依赖项
WebClient依赖于spring-boot-starter-webflux和Reactor,使用之前需要引入相关的依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>
3. WebClient 使用
使用WebClient我们需要按照如下几步来操作
- 创建WebClient实例
- 执行请求
- 处理返回数据
3.1 创建WebClient实例
构建WebClient有三种方法:
第一种,使用默认配置构建WebClient
WebClient client1 = WebClient.create();