【问题标题】:Spring Boot WebClient Connection and Read TimeoutSpring Boot WebClient 连接和读取超时
【发布时间】:2021-12-27 06:49:25
【问题描述】:

目前我的 post 和 get 请求是通过 WebClients 处理的,它在 Spring Boot 中具有公共连接和读取超时。我有 5 个不同的类,每个类都需要自己的一组连接和读取超时。我不想创建 5 个不同的 WebClient,而是使用相同的 Webclient,但是在从特定类发送帖子或获取请求时,指定所需的连接和读取超时。有什么方法可以实现吗?

我当前的 WebClient:

    @Bean
    public WebClient getWebClient(WebClient.Builder builder){

        HttpClient httpClient = HttpClient.newConnection()
                .tcpConfiguration(tcpClient -> {
                    tcpClient = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout*1000);
                    tcpClient = tcpClient.doOnConnected(conn -> conn
                            .addHandlerLast(new ReadTimeoutHandler(readTimeout, TimeUnit.SECONDS)));
                    return tcpClient;
                }).wiretap(true);

        ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);

        return builder.clientConnector(connector).build();
    }

我正在使用的发布请求:

public WebClientResponse httpPost(String endpoint, String requestData, Map<String, Object> requestHeader) {

        ClientResponse res = webClient.post().uri(endpoint)
                .body(BodyInserters.fromObject(requestData))
                .headers(x -> {
                    if(requestHeader != null && !requestHeader.isEmpty()) {
                        for (String s : requestHeader.keySet()) {
                            x.set(s, String.valueOf(requestHeader.get(s)));
                        }
                    }
                })
                .exchange()
                .doOnSuccess(x -> log.info("response code = " + x.statusCode()))
                .block();

        return convertWebClientResponse(res);
    }

【问题讨论】:

  • 您可以在 WebClient 及其各自的 setter 方法中拥有超时成员。在发送每个请求之前,您可以使用 setter 更改超时值,然后调用适当的 Get 和 Post 请求。

标签: java spring-boot spring-webclient


【解决方案1】:

您可以在 WebClient 中配置请求级超时。

 webClient.get()
   .uri("https://baeldung.com/path")
   .httpRequest(httpRequest -> {
   HttpClientRequest reactorRequest = httpRequest.getNativeRequest();
   reactorRequest.responseTimeout(Duration.ofSeconds(2));
 });

现在您可以做的是,根据请求,您可以从属性文件中添加这些值,也可以对它们进行硬编码。

参考:-https://www.baeldung.com/spring-webflux-timeout

【讨论】:

  • 所以在 Duration.ofSeconds() 我通过了所需的超时。但是在我的配置中,我为连接和读取超时添加了 tcpClient 选项,我仍然不确定如何使用它来添加它
  • 这是您的默认超时。这将覆盖它们。
  • 是的,但我需要 tcp 级别超时。这不是一回事
  • 是一样的。该请求将使用提供的配置打开 TCP 连接。您也可以添加某种策略模式来修改它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 2019-08-14
  • 2011-12-05
  • 2017-10-29
  • 2018-06-14
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多