用 WebClient 代替 RestTemplate

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

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

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

用 WebClient 代替 RestTemplate

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

用 WebClient 代替 RestTemplate

平时在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));  // &#x540E;&#x6267;&#x884C;
        System.out.println(1); // &#x5148;&#x6267;&#x884C;
        return "hello";
    }

    /**
     * RestTemplate
     */
    @GetMapping("/hi")
    public String hi() {
        RestTemplate restTemplate = new RestTemplate();
        String resp = restTemplate.getForEntity(url, String.class).getBody();
        System.out.println(resp); // &#x5148;&#x6267;&#x884C;
        System.out.println(1);  // &#x540E;&#x6267;&#x884C;
        return resp;
    }
}

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

Original: https://www.cnblogs.com/cjsblog/p/16145608.html
Author: 废物大师兄
Title: 用 WebClient 代替 RestTemplate

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/613093/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球