Spring Boot中文參考指南 36、使用 WebClient 調用 REST 服務

下一篇[未完待續]

<code>英文原文:https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-webclient.html/<code>

<code>GitHub:https://github.com/jijicai/Spring/tree/master/spring-boot/<code>

36、使用 WebClient 調用 REST 服務

如果你的類路徑上有 Spring WebFlux,你也可以選擇使用 WebClient 調用遠程 REST 服務。與 RestTemplate 相比,該客戶端具有更多函數式感覺,並且完全是反應式的。你可以在 Spring Framework 文檔的專用部分了解有關 WebClient 的更多信息。(https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/web-reactive.html#webflux-client )

Spring Boot 為你創建並預配置 WebClient.Builder;強烈建議將其注入組件並使用它創建 WebClient 實例。Spring Boot 正在配置該構建器以共享 HTTP 資源,以與服務器相同的方式表示編解碼器設置 (請參見 WebFlux HTTP 編解碼器自動配置),等等。(https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-developing-web-applications.html#boot-features-webflux-httpcodecs )

以下代碼展示了一個典型示例:

<code>@Service
public class MyService {

private final WebClient webClient;

public MyService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://example.org").build();
}

public Mono<details> someRestCall(String name) {
return this.webClient.get().uri("/{name}/details", name)
.retrieve().bodyToMono(Details.class);
}

}
/<details>/<code>

36.1、WebClient 運行時

根據應用程序類路徑上可用的庫,Spring Boot 將自動檢測用於驅動 WebClient 的 ClientHttpConnector。目前,支持 Reactor Netty 和 Jetty RS 客戶端。

spring-boot-starter-webflux 默認依賴於 io.projectreactor.netty:reactor-netty,它同時提供服務器和客戶端實現。如果你選擇使用 Jetty 作為一個反應式服務器,那麼你應該添加對 Jetty Reactive HTTP 客戶端庫 org.eclipse.jetty:jetty-reactive-httpclient 的依賴。對服務器和客戶端使用相同的技術有其優點,因為它將在客戶端和服務器之間自動共享 HTTP 資源。

開發者可以通過提供自定義 JettyResourceFactory 或 ReactorResourceFactory bean 來覆蓋 Jetty 或 Reactor Netty 的資源配置-這將應用於客戶端和服務器。

如果你希望為客戶端覆蓋該選擇,則可以定義自己的 ClientHttpConnector bean 並完全控制客戶端配置。

你可以在 Spring Framework 參考文檔中瞭解有關 WebClient 配置選項的更多信息。

36.2、WebClient 定製

WebClient 定製有三種主要方法,具體情況基本上取決於你希望如何應用定製。

要儘可能縮小任何自定義的範圍,請注入自動配置的 WebClient.Builder,然後按需調用其方法。WebClient.Builder 實例是有狀態的: 構建器上的任何更改都會反映在隨後使用它創建的所有客戶端中。如果要使用同一構建器創建多個客戶端,還可以考慮使用 WebClient.builder other=builder.clone(); 克隆該構建器。

要對所有 WebClient.Builder 實例進行應用程序範圍的附加自定義,可以聲明 WebClientCustomizer bean 並在注入點本地更改 WebClient.Builder。

最後,你可以返回到原始 API 並使用 WebClient.create()。在這種情況下,不會應用自動配置或 WebClientCustomizer。

下一篇[未完待續]