在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