Spring Boot(14)——使用WebClient

使用WebClient

WebClient是Spring WebFlux模塊提供的一個非阻塞的基於響應式編程的進行Http請求的客戶端工具,從Spring5.0開始提供。Spring Boot應用中添加如下依賴將自動添加Spring WebFlux依賴,從而可以使用WebClient。

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

Spring Boot的org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration.會自動配置一個WebClient.Builder類型的bean。在需要使用WebClient的時候在程序中注入一個WebClient.Builder對象,通過對它進行自定義來生成對應的WebClient對象,從而作爲客戶端進行Web請求。下面是一個簡單的示例。

@Service
public class WebClientService {

    private final WebClient webClient;
    
    public WebClientService(WebClient.Builder builder) {
        this.webClient = builder.baseUrl("http://localhost:8081").build();
    }
    
    public String getJson() {
        return this.webClient.get().uri("hello/json").retrieve().bodyToMono(String.class).block();
    }
    
}

WebClientCustomizer

Spring Boot提供了org.springframework.boot.web.reactive.function.client.WebClientCustomizer接口定義,它允許我們通過實現該接口對WebClient進行一些通用的自定義,然後將該接口的實現類定義爲Spring bean。Spring Boot在創建WebClient實例時會在bean容器中尋找WebClientCustomizer類型的bean,一一調用它們的customize()方法以便對WebClient進行一些自定義。下面的代碼中就對WebClient添加了一個默認的Cookie和一個默認的Header。

@Component
public class MyWebClientCustomizer implements WebClientCustomizer {

    @Override
    public void customize(Builder webClientBuilder) {
        webClientBuilder.defaultCookie("cookieName", "cookieValue").defaultHeader("headerName", "headerValue");
    }

}

CodecCustomizer

如果需要定義自己的編解碼工具,則可以實現org.springframework.boot.web.codec.CodecCustomizer接口,把它定義爲Spring bean,通過其customize()方法可以獲取到org.springframework.http.codec.CodecConfigurer對象,從而可以註冊新的編解碼工具,或對現有的編解碼工具進行替換等。

本文主要介紹在Spring Boot工程中如何應用WebClient,關於WebClient的基本用法可以參考http://elim.iteye.com/blog/2427658

(注:本文基於Spring Boot 2.0.3所寫)

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