Set a Timeout in Spring 5 Webflux WebClient

  • idle timeout: 闲置 超时时间
  • Response Timeout
    The response timeout is the time we wait to receive a response after sending a request.
  • connection timeout:
    The connection timeout is a period within which a connection between a client and a server must be established.
  • read & write timeout:
    A read timeout occurs when no data was read within a certain period of time, while the write timeout when a write operation cannot finish at a specific time.

Configuring Timeouts via HTTP Client

Response Timeout 响应超时

响应超时是我们 在发送请求后等待接收响应的时间。我们可以使用responseTimeout()方法为客户端配置

The response timeout is the time we wait to receive a response after sending a request. We can use the responseTimeout() method to configure it for the client:
In this example, we configure the timeout for 1 second. Netty doesn’t set the response timeout by default.

After that, we can supply the HttpClient to the Spring WebClient:

1
2
3
4
5
6
HttpClient client = HttpClient.create()
.responseTimeout(Duration.ofSeconds(1));

WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();

After doing that, the WebClient inherits all the configurations provided by the underlying HttpClient for all requests sent.
这样做之后,WebClient 继承了底层HttpClient 为发送的所有请求提供的所有配置。

Connection Timeout

连接超时是必须在客户端和服务器之间建立连接的时间段。

The connection timeout is a period within which a connection between a client and a server must be established. We can use different channel options keys and the option() method to perform the configuration:

1
2
HttpClient client = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

提供的值以毫秒为单位,因此我们将超时配置为 10 秒。默认情况下,Netty 将该值设置为 30 秒。

此外,我们可以配置keep-alive选项,它会在连接空闲时发送TCP检查探测:

1
2
3
4
5
6
HttpClient client = HttpClient.create()
.option(ChannelOption.SO_KEEPALIVE, true)
.option(EpollChannelOption.TCP_KEEPIDLE, 300)
.option(EpollChannelOption.TCP_KEEPINTVL, 60)
.option(EpollChannelOption.TCP_KEEPCNT, 8);
// create WebClient...

因此,我们启用了保持活动检查以在空闲 5 分钟后以 60 秒的间隔进行探测。我们还将连接下降之前的最大探测数设置为 8。

当在给定时间内未建立连接或断开连接时,将抛出ConnectTimeoutException。

Read and Write Timeout

A read timeout occurs when no data was read within a certain period of time, while the write timeout when a write operation cannot finish at a specific time. The HttpClient allows to configure additional handlers to configure those timeouts:

读超时是指在一定时间内没有读到数据,写超时是写操作无法在特定时间完成。该HttpClient的允许配置更多的处理器配置这些超时:

1
2
3
4
5
6
HttpClient client = HttpClient.create()
.doOnConnected(conn -> conn
.addHandler(new ReadTimeoutHandler(10, TimeUnit.SECONDS))
.addHandler(new WriteTimeoutHandler(10)));

// create WebClient...

在这种情况下,我们通过doOnConnected()方法配置了一个连接的回调,我们在其中创建了额外的处理程序。为了配置超时,我们添加了ReadTimeOutHandler 和WriteTimeOutHandle r实例。我们将它们都设置为 10 秒。

这些处理程序的构造函数接受两种参数变体。对于第一个,我们提供了一个TimeUnit规范的数字,而第二个将给定的数字转换为秒。

底层 Netty 库相应地提供ReadTimeoutException和WriteTimeoutException类来处理错误。

参考文章

评论