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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章