用 WebClient 代替 RestTemplate

RestTemplate是用于执行 HTTP 请求的同步客户端,通过底层 HTTP 客户端库(例如 JDK HttpURLConnection、Apache HttpComponents 等)公开一个简单的模板方法 API。

RestTemplate 通过 HTTP 方法为常见场景提供模板

注意:从Spring 5.0开始,该类处于维护模式,只有较小的更改请求和错误被接受。 请考虑使用 org.springframework.web.reactive.client.WebClient,它具有更现代的 API 并支持同步、异步和流式处理方案。

WebClient是用于执行 HTTP 请求的非阻塞、响应式客户端,通过底层 HTTP 客户端库(如 Reactor Netty)公开流畅的响应式 API。

平时在Spring Boot项目开发过程中,可以多使用WebClient来进行异步远程调用

举个例子:

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

package com.example.demo413;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @Author ChengJianSheng
 * @Date 2022/4/13
 */
@RestController
public class HelloController {

    private String url = "http://localhost:8093/soas-enterprise/hello/hi?name=zhangsan";  // Thread.sleep(5000)

    /**
     * WebClient
     */
    @GetMapping("/hello")
    public String hello() {
        Mono resp = WebClient.create().get().uri(url).retrieve().bodyToMono(String.class);
        resp.subscribe(e-> System.out.println(e));  // 后执行
        System.out.println(1); // 先执行
        return "hello";
    }

    /**
     * RestTemplate
     */
    @GetMapping("/hi")
    public String hi() {
        RestTemplate restTemplate = new RestTemplate();
        String resp = restTemplate.getForEntity(url, String.class).getBody();
        System.out.println(resp); // 先执行
        System.out.println(1);  // 后执行
        return resp;
    }
}

观察控制台,看代码执行顺序

posted @ 2022-04-14 17:17  废物大师兄  阅读(1567)  评论(0编辑  收藏  举报