如何在Spring 5 WebFlux WebClient中设置超时

我正在尝试在WebClient上设置超时,这是当前代码:

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();

我需要添加超时和池策略,我在想这样的事情:

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();

但是我不知道如何在我的webclient中设置httpClient

回答:

WebFlux WebClient不使用Apache Commons HTTP Client。虽然你可能可以通过custom实现一个解决方案ClientHttpConnector。现有ReactorClientHttpConnector基于Netty。因此,考虑使用Netty选项来配置客户端,例如:

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

以上是 如何在Spring 5 WebFlux WebClient中设置超时 的全部内容, 来源链接: utcz.com/qa/432832.html

回到顶部