【SpringBoot WEB 系列】WebClient 之基础使用姿势
在使用AsyncRestTemplate
来实现网络异步请求时,当时提到在 Spring5+之后,建议通过 WebClient 来取代 AsyncRestTemplate 来实现异步网络请求;
那么 WebClient 又是一个什么东西呢,它是怎样替代AsyncRestTemplate
来实现异步请求的呢,接下来我们将进入 Spring Web 工具篇中,比较重要的 WebClient 系列知识点,本文为第一篇,基本使用姿势一览
I. 项目环境
我们依然采用 SpringBoot 来搭建项目,版本为 2.2.1.RELEASE
, maven3.2
作为构建工具,idea
作为开发环境
1. pom 依赖
SpringBoot 相关的依赖就不贴出来了,有兴趣的可以查看源码,下面是关键依赖
<dependencies>
<!-- 请注意这个引入,是最为重要的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
请注意一下上面的两个依赖包,对于使用WebClient
,主要需要引入spring-boot-starter-webflux
包
2. 测试 REST 接口
接下来我们直接在这个项目中写几个用于测试的 REST 接口,因为项目引入的 webflux 的依赖包,所以我们这里也采用 webflux 的注解方式,新增用于测试的 GET/POST 接口
对于 WebFlux 用法不太清楚的小伙伴也没有关系,WebClient 的发起的请求,后端是基于传统的 Servlet 也是没有问题的;关于 WebFlux 的知识点,将放在 WebClient 系列博文之后进行介绍
@Data
public class Body {
String name;
Integer age;
}
@RestController
public class ReactRest {
@GetMapping(path = "header")
public Mono<String> header(@RequestHeader(name = "User-Agent") String userAgent,
@RequestHeader(name = "ck", required = false) String cookie) {
return Mono.just("userAgent is: [" + userAgent + "] ck: [" + cookie + "]");
}
@GetMapping(path = "get")
public Mono<String> get(String name, Integer age) {
return Mono.just("req: " + name + " age: " + age);
}
@GetMapping(path = "mget")
public Flux<String> mget(String name, Integer age) {
return Flux.fromArray(ne