【SpringBoot WEB 系列】WebClient 之同步与异步
回顾一下最开始介绍 WebClient 的使用姿势之前,我们介绍了 AsyncRestTemplate 来实现异步的网络请求;但是在 Spring5 之后,官方推荐使用 WebClient 来替换 AsyncRestTemplate 实现异步请求;所以一般来讲,WebClient 适用于异步的网络访问,但是,假设我需要同步获取返回结果,可行么?
(本文也是webclient系列中最后一篇,接下来进WebFlux系列教程)
I. 项目环境
本项目借助SpringBoot 2.2.1.RELEASE
+ maven 3.5.3
+ IDEA
进行开发
1. 依赖
使用 WebClient,最主要的引入依赖如下(省略掉了 SpringBoot 的相关依赖,如对于如何创建 SpringBoot 项目不太清楚的小伙伴,可以关注一下我之前的博文)
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webfluxartifactId>
dependency>
2. 测试接口
@GetMapping(path = "get")
public Mono get(String name, Integer age) {
return Mono.just("req: " + name + " age: " + age);
}
@GetMapping(path = "mget")
public Flux mget(String name, Integer age) {
return Flux.fromArray(new String[]{"req name: " + name, "req age: " + age});
}
II. 同步返回
需要同步返回结果还是比较简单的,获取对应的 Mono/Flux 之后调用一下block()
方法即可,但是需要注意,这里也有一个潜在的坑
1. 实现方式
public void sync() {
// 同步调用的姿势
// 需要特别注意,这种是使用姿势,不能在响应一个http请求的线程中执行;
// 比如这个项目中,可以通过 http://127.0.0.1:8080/test 来调用本类的测试方法;但本方法如果被这种姿势调用,则会抛异常;
// 如果需要正常测试,可以看一下test下的调用case
WebClient webClient = WebClient.create("http://127.0.0.1:8080");
String ans = webClient.get().uri("/get?name=一灰灰").retrieve().bodyToMono(String.class).block();
System.out.println("block get Mono res: " + ans);
Map uriVariables = new HashMap<>(4);
uriVariables.put("p1", "一灰灰");
uriVariables.put("p2", 19);
List fans =
webClient.get().uri("/mget?name={p1}&age={p2}", uriVariables).retrieve().bodyToFlux(String.class)
.collectList().block();
System.out.println("block get Flux res: " + fans);
}
项目启动之后,我们写一个测试类来调用这个方法
@Test
public void sync() {
WebClientTutorial web = new WebClientTutorial();
web.sync();
}
如果我们换成下面这种写法,就会报错了
@GetMapping(path = "test")
public String test() {
WebClientTutorial web = new WebClientTutorial();
web.sync();
return "over";
}
III. 其他
0. 项目
系列博文
- 【WEB 系列】WebClient 之策略设置
- 【WEB 系列】WebClient 之非 200 状态码信息捕获
- 【WEB 系列】WebClient 之 retrieve 与 exchange 的使用区别介绍
- 【WEB 系列】WebClient 之超时设置
- 【WEB 系列】WebClient 之 Basic Auth 授权
- 【WEB 系列】WebClient 之请求头设置
- 【WEB 系列】WebClient 之文件上传
- 【WEB 系列】WebClient 之基础使用姿势
源码
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源码:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/222-web-client
1. 一灰灰 Blog
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现 bug 或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
- 一灰灰 Blog 个人博客 https://blog.hhui.top
- 一灰灰 Blog-Spring 专题博客 http://spring.hhui.top