javareactor-netty

How can I set connect/write/read timeout on HttpClient


I need to write a library works for spring-boot-2.1.6 which uses reactor-netty:0.8.9.RELEASE.

How can I set connect/write/read timeout on an instance of HttpClient and/or on an instance of TcpClient?

I just found that I can set a connection timeout like this.

final HttpClient httpClient = HttpClient.create()
        .tcpConfiguration(tc -> {
            Optional.ofNullable(getConnectTimeout())
                    .map(Duration::toMillis)
                    .map(Math::toIntExact)
                    .ifPresent(ct -> {
                        tc.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ct);
                    });
            return tc;
        });

Is that right? And how can I set write/read time out?


Solution

  • you can set read/write timeout like this:

    import io.netty.channel.Channel;
    import io.netty.handler.timeout.ReadTimeoutHandler;
    import io.netty.handler.timeout.WriteTimeoutHandler;
    import reactor.netty.http.client.HttpClient;
    import reactor.netty.tcp.TcpClient;
    
    import java.time.Duration;
    import java.util.concurrent.TimeUnit;
    
    public class TimeoutSetting {
    
        private HttpClient createHttpClient(Duration connectTimeout, Duration readTimeout, Duration writeTimeout) {
            return HttpClient.create()
                    .tcpConfiguration(tcpClient -> tcpClient
                            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectTimeout.toMillis()))
                            .doOnConnected(connection -> {
                                connection.addHandlerLast(new ReadTimeoutHandler(Math.toIntExact(readTimeout.toMillis()), TimeUnit.MILLISECONDS));
                                connection.addHandlerLast(new WriteTimeoutHandler(Math.toIntExact(writeTimeout.toMillis()), TimeUnit.MILLISECONDS));
                            }));
        }
    
    }
    

    Use it like this:

        HttpClient httpClient = createHttpClient(
            Duration.ofSeconds(10), // Connect timeout
            Duration.ofSeconds(30), // Read timeout
            Duration.ofSeconds(20)  // Write timeout
        );