4

What is the correct way to set a (connection) timeout for the (default) WebClient?

Is it enough to just use Mono#timeout(Duration) method on the resulting Mono (or Flux)? 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!)

Justus87
  • 141
  • 1
  • 3
  • 1
    Possible duplicate of [Spring 5 webflux how to set a timeout on Webclient](https://stackoverflow.com/questions/46235512/spring-5-webflux-how-to-set-a-timeout-on-webclient) – pvpkiran Jan 04 '18 at 14:16
  • I know the post you mentioned; even the accepted answer does *not* work (and is so ugly). – Justus87 Jan 04 '18 at 14:23

2 Answers2

10

As of Reactor Netty 0.8 and Spring Framework 5.1, you can set connection, read & write timeouts like the following:

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();
Sophia Price
  • 848
  • 11
  • 17
2

For now, WebClient does not offer that option as a top-level configuration option. You have to configure that at the underlying HTTP client library.

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();
Brian Clozel
  • 56,583
  • 15
  • 167
  • 176