针对Spring Web客户端每个请求的基础上配置超时?

时间:2019-02-02 15:32:26

标签: spring spring-boot spring-webflux project-reactor

我知道Spring 5 webflux how to set a timeout on Webclient,但这会为所有请求全局配置超时。我正在寻找一种方法来配置每个请求的基础上的超时。即像这样的东西(伪代码不起作用):

WebClient client = ...

// Call 1
client.timeout(5, TimeUnit.SECONDS).contentType(APPLICATION_JSON).syncBody(..).exchange(). ..

// Call 2
client.timeout(4, TimeUnit.SECONDS).contentType(APPLICATION_JSON).syncBody(..).exchange(). 

timeout函数由式展示我后。我该如何实现?这也是很重要的资源是在超时正确地清理。

如果有什么不同,我正在使用Netty(reactor-netty 0.8.4.RELEASE):

HttpClient httpClient = HttpClient.create(). ...;

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

1 个答案:

答案 0 :(得分:1)

这两个答案清楚地说明了这一点。

set-timeout-in-spring-webflux-webclient
spring-5-webflux-how-to-set-a-timeout-on-webclient

此外,如果你正在寻找突变的选项,

您可以像下面这样

 TcpClient tcpClient = TcpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
                .doOnConnected(connection ->
                        connection.addHandlerLast(new ReadTimeoutHandler(10))
                                .addHandlerLast(new WriteTimeoutHandler(10)));
        return this.webClient
                .mutate()
                .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
                .build()
                .get()