[英]Spring 5 webflux how to set a timeout to an existing Webclient
[英]set timeout in Spring WebFlux webclient
我正在使用 Spring Webflux WebClient 从我的 Spring 启动应用程序进行 REST 调用。 并且每次都在 30 秒内超时。
这是我尝试在 Spring webfulx 的 WebClient 中设置套接字超时的一些代码。
- ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options -> options
.option(ChannelOption.SO_TIMEOUT, 600000).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 600000));
- ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
options -> options.afterChannelInit(chan -> {
chan.pipeline().addLast(new ReadTimeoutHandler(600000));
}));
- ReactorClientHttpConnector connector1 = new ReactorClientHttpConnector(options -> options
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 600000).afterNettyContextInit(ctx -> {
ctx.addHandlerLast(new ReadTimeoutHandler(600000, TimeUnit.MILLISECONDS));
}));
并尝试使用“clientConnector”方法在“WebClient”中添加上述连接器设置。
并尝试将超时设置如下:
webClient.get().uri(builder -> builder.path("/result/{name}/sets")
.queryParam("q", "kind:RECORDS")
.queryParam("offset", offset)
.queryParam("limit", RECORD_COUNT_LIMIT)
.build(name))
.header(HttpHeaders.AUTHORIZATION, accessToken)
.exchange().timeout(Duration.ofMillis(600000))
.flatMap(response -> handleResponse(response, name, offset));
以上选项都不适合我。
我正在使用 org.springframework.boot:spring-boot-gradle-plugin:2.0.0.M7 其内部依赖于 org.springframework:spring-webflux:5.0.2.RELEASE。
请在这里提出建议,如果我在这里做错了什么,请告诉我。
我试过重现这个问题,但不能。 使用 reactor-netty 0.7.5.RELEASE。
我不确定你说的是哪个超时。
可以使用ChannelOption.CONNECT_TIMEOUT_MILLIS
配置连接超时。 我在“连接”日志消息和实际错误之间有 10 秒的时间:
WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(options -> options
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)))
.build();
webClient.get().uri("http://10.0.0.1/resource").exchange()
.doOnSubscribe(subscription -> logger.info("connecting"))
.then()
.doOnError(err -> logger.severe(err.getMessage()))
.block();
如果您在谈论读/写超时,那么您可以查看 Netty 的ReadTimeoutHandler
和WriteTimeoutHandler
。
一个完整的例子可能如下所示:
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(options ->
options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10)
.onChannelInit(channel -> {
channel.pipeline().addLast(new ReadTimeoutHandler(10))
.addLast(new WriteTimeoutHandler(10));
return true;
}).build());
从 Reactor Netty 0.8 和 Spring Framework 5.1 开始,配置现在如下所示:
TcpClient tcpClient = TcpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
.doOnConnected(connection ->
connection.addHandlerLast(new ReadTimeoutHandler(10))
.addHandlerLast(new WriteTimeoutHandler(10)));
WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
.build();
也许将以下内容添加到您的application.properties
将提供有关 HTTP 级别发生的事情的更多信息:
logging.level.reactor.ipc.netty.channel.ContextHandler=debug
logging.level.reactor.ipc.netty.http.client.HttpClient=debug
由于HttpClient.from(tcpClient)
现在已在最新的HttpClient.from(tcpClient)
被弃用,并将在 v1.1.0 中移除)。 您可以使用responseTimeout()
并忽略您在其他代码中看到的过多 HTTP 连接配置,并且此实现适用于旧的和新的。
创建 HttpClient
HttpClient httpClient = HttpClient.create().responseTimeout(Duration.ofMillis(500)); // 500 -> timeout in millis
使用 webClient builder fxn .clientConnector()
将 httpClient 添加到 webclient
WebClient
.builder()
.baseUrl("http://myawesomeurl.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
此外,网站上提供的大部分实现都没有被弃用,以确保您没有使用已弃用的实现,您可以查看此链接。
仅供参考:对于较旧的 netty 版本(即 < v0.9.11 版本), responseTimeout()
幕后使用 tcpConfiguration() ,这在新版本中已弃用。 但是 responseTimeout() 使用了 >=v0.9.11 中的新实现,因此即使您将来更改项目的 netty 版本,您的代码也不会中断。
注意:如果您有时使用 spring 默认附带的旧 netty 版本,您可能也可以使用 Brian 的实现。 (虽然不确定)
如果您想了解更多关于responseTimeout(),它是如何工作的,你可以查看源代码,在这里和这里或GitHub的要点在这里。
正如@im_bhatman 提到的,每个HttpClient.from(TcpClient)
方法已被弃用,这里有一种使用旧方法的方法。
// works for Spring Boot 2.4.0, 2.4.1, and 2.4.2
// doesn't work for Spring Boot 2.3.6, 2.3.7, and 2.3.8
HttpClient httpClient = HttpClient.create()
//.responseTimeout(Duration.ofSeconds(READ_TIMEOUT_SECONDS))
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIME_MILLIS)
.doOnConnected(c -> {
c.addHandlerLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS))
.addHandlerLast(new WriteTimeoutHandler(WRITE_TIMEOUT_SECONDS));
});
ClientConnector clientConnector = new ReactorClientHttpConnector(httpClient);
WebClient webClient = WebClient.builder()
.clientConnector(clientConnector)
...
.build();
我不确定
HttpClient#responseTimeout(...)
HttpClient#doOnConnected(c -> c.addHandler(new ReadTimeoutHandler(...)))
请参阅以下代码块以设置超时并使用 webclient 重试
.retrieve()
.onStatus(
(HttpStatus::isError), // or the code that you want
(it -> handleError(it.statusCode().getReasonPhrase())) //handling error request
)
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5))
.retryWhen(
Retry.backoff(retryCount, Duration.ofSeconds(5))
.filter(throwable -> throwable instanceof TimeoutException)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.