如何在Spring 5 WebFlux WebClient中设置超时
我正在尝试在WebClient上设置超时,这是当前代码:
I'm trying to set timeout on my WebClient, here is the current code :
SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(opt -> {
opt.sslContext(sslContext);
HttpClientOptions option = HttpClientOptions.builder().build();
opt.from(option);
});
return WebClient.builder().clientConnector(httpConnector).defaultHeader("Authorization", xxxx)
.baseUrl(this.opusConfig.getBaseURL()).build();
我需要添加超时以及池化策略,我在想这样的事情:
I need to add timeout and also pooling strategy, I was thinking of something like that :
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(this.applicationConfig.getHttpClientMaxPoolSize());
cm.setDefaultMaxPerRoute(this.applicationConfig.getHttpClientMaxPoolSize());
cm.closeIdleConnections(this.applicationConfig.getServerIdleTimeout(), TimeUnit.MILLISECONDS);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.applicationConfig.getHttpClientSocketTimeout())
.setConnectTimeout(this.applicationConfig.getHttpClientConnectTimeout())
.setConnectionRequestTimeout(this.applicationConfig.getHttpClientRequestTimeout()).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
但是我不知道如何在我的网络客户端中设置httpClient
But I can't figure out how to set the httpClient in my webclient
WebFlux WebClient
不使用Apache Commons HTTP Client.尽管您可能可以通过自定义ClientHttpConnector
实现一种解决方案.现有的ReactorClientHttpConnector
基于Netty.因此,考虑使用Netty选项配置客户端,例如:
The WebFlux WebClient
doesn't use Apache Commons HTTP Client. Although you might be able to implement one solution via custom ClientHttpConnector
. The existing ReactorClientHttpConnector
is based on the Netty. So, consider to use Netty options to configure the client, e.g.:
ReactorClientHttpConnector connector =
new ReactorClientHttpConnector(options ->
options.option(ChannelOption.SO_TIMEOUT, this.applicationConfig.getHttpClientConnectTimeout()));
或
.onChannelInit(channel -> channel.config().setConnectTimeoutMillis(this.applicationConfig.getHttpClientConnectTimeout()))
更新
我们也可以使用ReadTimeoutHandler
:
.onChannelInit(channel ->
channel.pipeline()
.addLast(new ReadTimeoutHandler(this.applicationConfig.getHttpClientConnectTimeout())))