Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set connection timeout using Spring Webflux Reactive WebClient

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!)

like image 436
Justus87 Avatar asked Dec 13 '22 19:12

Justus87


1 Answers

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();
like image 82
Sophia Price Avatar answered Apr 26 '23 09:04

Sophia Price