用 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;
    }
}

觀察控制台,看代碼執行順序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM