簡體   English   中英

Spring 5 webflux 如何為現有的 Webclient 設置超時

[英]Spring 5 webflux how to set a timeout to an existing Webclient

我在我的配置類中定義了一個 WebClient bean。 它涉及對其連接器的大量配置(包括設置 SSL、代理等)。

    @Bean
    @Primary
    @Scope("prototype")
    public WebClient webClient()
    {
       SslContextBuilder builder = SslContextBuilder.forClient();
        HttpClient httpClient = HttpClient
                .create(ConnectionProvider.fixed("webClientPool", maxConnections))
                ...

        ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
        WebClient webClient = WebClient.builder()
                .clientConnector(connector)
                .exchangeStrategies(getExchangeStrategies())
                .build();
        return webClient;

在注入此 WebClient 的 bean 之一中,我想設置不同的超時。

我想使用webClient.mutate().clientConnector(...)方法,但這需要我從頭開始設置整個配置,只是為了設置超時。 不幸的是,WebClient 和 HttpClient 沒有 .getxxx() 方法可以幫助我將舊的客戶端配置復制到新的配置中。

我想有一種方法為變異的 WebClient 只設置 tcp-client 的超時選項。 有沒有辦法做到這一點?

根據文檔

WebClient.Builder mutate()

返回一個生成器以創建一個新的WebClient,其設置是從當前WebClient復制的。

將返回具有所有先前設置的新生成器,因此您無需復制任何內容。

網絡客戶端變異

如果要盡可能減少配置,可以:

定義一個@Bean ,在其中盡可能多地配置HttpClient.Builder ,以便稍后可以自動連接HttpClient.Builder

然后,您定義2個Web客戶端,這些Web客戶端會自動綁定到httpclient中,並將httpclient.build()完成到每個webclient中。

或定義一個Web客戶端,然后在需要修改的Web客戶端的類中,將其注入到Web客戶端和httpclient.builder中,並完成配置並更改Web客戶端。

您可以使用reactor.core.publisher.Mono#timeout(java.time.Duration)方法,而不是修改WebClient

webClient.get()
        .uri("http://whatever/path")
        .retrieve()
        .bodyToMono(String.class)
        .timeout(Duration.ofMillis(3000));

編輯:基礎連接將被清除

21:53:11.380 [parallel-1] DEBUG org.springframework.web.reactive.function.client.ExchangeFunctions - [7ed3df3b] Cancel signal (to close connection)
21:53:11.382 [reactor-http-epoll-5] DEBUG reactor.netty.http.client.HttpClient - [id: 0xd97cbbde, L:/127.0.0.1:39140 - R:localhost/127.0.0.1:44451] CLOSE
21:53:11.384 [reactor-http-epoll-5] DEBUG reactor.netty.resources.PooledConnectionProvider - [id: 0xd97cbbde, L:/127.0.0.1:39140 ! R:localhost/127.0.0.1:44451] Channel cleaned, now 0 active connections and 1 inactive connections

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM