0

I'm aware of Spring 5 webflux how to set a timeout on Webclient but this configures the timeout globally for all requests. I'm looking for a way to configure the timeout on a per request basis. I.e. something like this (pseudo-code that doesn't work):

WebClient client = ...

// Call 1
client.timeout(5, TimeUnit.SECONDS).contentType(APPLICATION_JSON).syncBody(..).exchange(). ..

// Call 2
client.timeout(4, TimeUnit.SECONDS).contentType(APPLICATION_JSON).syncBody(..).exchange(). 

The timeout function is made-up to demonstrate what I'm after. How can I achieve this? It's also important that resources are cleaned up properly on timeout.

If it makes any difference I'm using Netty (reactor-netty 0.8.4.RELEASE):

HttpClient httpClient = HttpClient.create(). ...;

 WebClient webClient = WebClient.builder()
          .clientConnector(new ReactorClientHttpConnector(httpClient))
          .build();
Johan
  • 37,479
  • 32
  • 149
  • 237

1 Answers1

2

These two answers clearly explains it.

set-timeout-in-spring-webflux-webclient
spring-5-webflux-how-to-set-a-timeout-on-webclient.

Additionally if you are looking to mutate the options,

you could do like below,

 TcpClient tcpClient = TcpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
                .doOnConnected(connection ->
                        connection.addHandlerLast(new ReadTimeoutHandler(10))
                                .addHandlerLast(new WriteTimeoutHandler(10)));
        return this.webClient
                .mutate()
                .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
                .build()
                .get()

Barath
  • 5,093
  • 1
  • 17
  • 42
  • 1
    Thanks, but is mutate fast enough to be used for virtually every request in a highly concurrent environment? – Johan Feb 03 '19 at 05:43
  • 1
    Technically it is not good to mutate for every request, it will be better if you create different beans of web client with req timeout settings( kind of factory design pattern) and use it appropriately. – Barath Feb 03 '19 at 06:21
  • In my experience creating a new ReactorClientHttpConnector for every request can lead to a memory leak – mjj1409 Jan 14 '23 at 13:25