简体   繁体   English

使用Spring Webflux Reactive WebClient设置连接超时

[英]Set connection timeout using Spring Webflux Reactive WebClient

What is the correct way to set a (connection) timeout for the (default) WebClient? 为(默认)WebClient设置(连接)超时的正确方法是什么?

Is it enough to just use Mono#timeout(Duration) method on the resulting Mono (or Flux)? 仅仅对生成的Mono(或Flux)使用Mono#timeout(Duration)方法是否足够? Or does this lead to a possible memory / connection leak? 或者这是否会导致内存/连接泄漏?

Thanks in advance! 提前致谢!

(The answers from Spring 5 webflux how to set a timeout on Webclient do not work!) Spring 5 webflux如何在Webclient上设置超时的答案不起作用!)

As of Reactor Netty 0.8 and Spring Framework 5.1, you can set connection, read & write timeouts like the following: 从Reactor Netty 0.8和Spring Framework 5.1开始,您可以设置连接,读取和写入超时,如下所示:

TcpClient tcpClient = TcpClient.create()
                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) // Connection Timeout
                 .doOnConnected(connection ->
                         connection.addHandlerLast(new ReadTimeoutHandler(10)) // Read Timeout
                                   .addHandlerLast(new WriteTimeoutHandler(10))); // Write Timeout
WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
    .build();

For now, WebClient does not offer that option as a top-level configuration option. 目前, WebClient不提供该选项作为顶级配置选项。 You have to configure that at the underlying HTTP client library. 您必须在底层HTTP客户端库中配置它。

So the answer to the other question is right. 所以另一个问题的答案是正确的。 But in your case, you probably need to change the connection timeout, not the socket timeout (or both). 但在您的情况下,您可能需要更改连接超时,而不是套接字超时(或两者)。

ReactorClientHttpConnector connector =
            new ReactorClientHttpConnector(options ->
                    options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000));
WebClient webClient = WebClient.builder().clientConnector(connector).build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM