9.同步与异步

一灰灰blogSpringBootWEB系列WebClientWebClient约 951 字大约 3 分钟

回顾一下最开始介绍WebClient的使用姿势之前,我们介绍了AsyncRestTemplate来实现异步的网络请求;但是在Spring5之后,官方推荐使用WebClient来替换AsyncRestTemplate实现异步请求;所以一般来讲,WebClient适用于异步的网络访问,但是,假设我需要同步获取返回结果,可行么?

I. 项目环境

本项目借助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA进行开发

1. 依赖

使用WebClient,最主要的引入依赖如下(省略掉了SpringBoot的相关依赖,如对于如何创建SpringBoot项目不太清楚的小伙伴,可以关注一下我之前的博文)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2. 测试接口

@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(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<String, Object> uriVariables = new HashMap<>(4);
    uriVariables.put("p1", "一灰灰");
    uriVariables.put("p2", 19);

    List<String> 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. 项目

系列博文

源码

Loading...