WebClient 在 Stream 中的每个元素调用上打开和关闭连接

问题描述 投票:0回答:1

尝试了解 spring webclient 如何处理对等点之间的连接。
使用以下代码时:
我与流中的元素有尽可能多的密切联系。
我预计当使用 http1.1 时,reactor-netty 会重用连接。 即使在尝试使用配置上的保持活动时,我也有相同的行为:

[d6b705e1]响应200 OK
[d6b705e1] 取消信号(关闭连接)

public WebClient webClient(WebClient.Builder builder) {
 return builder
  .baseUrl(config.getBaseurl())
  .clientConnector(new ReactorClientHttpConnector(
    HttpClient.create()
      .tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout))
      .secure(spec -> spec.sslContext(SslContextBuilder.forClient()))
  ))
  .build();
}

Flux<String> getIds() { ... }

Flux<Response> getResponses() {
  // here as many open and close connection as the return stream getIds 
  return getIds().flatMap(... // client.retrieve().bodyToMono(Reponse.class));
}
java spring-webflux reactor reactor-netty
1个回答
0
投票

我期望在使用 http1.1 时,reactor-netty 会重用连接。

如果可以的话,会的。以下面为例:

@RestController
public class MyController {

    private final WebClient wc;

    @Autowired
    public MyController(WebClient.Builder wcb) {
        wc = wcb
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .clientConnector(new ReactorClientHttpConnector(
                        HttpClient.create()
                                .tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000))
                                .secure(spec -> spec.sslContext(SslContextBuilder.forClient()))
                ))
                .build();
    }

    @GetMapping("/")
    public Mono<List<Body>> cookieSetter() {
        return Flux.range(1,10)
                .flatMap(i -> wc.get().uri("todos/" + i).retrieve().bodyToMono(Body.class))
                .collectList();
    }

    @Data
    static class Body {
        private String title;
    }

}

加载它,您会看到一堆

HTTP GET https://jsonplaceholder.typicode.com/todos/x
Response 200 OK
,但没有
Cancel signal (to close connection)
日志 - 它保持连接打开并重用它。

您没有提供完整的示例,但这里可能发生以下两种情况之一:

  • 您正在主动取消发布者(或者框架中的某些内容正在取消响应发布者),这会导致连接被关闭,作为此取消的副作用。
  • 您连接的服务器不支持保持活动状态。请注意,这是一个“可选”功能,服务器不必支持它,即使在 HTTP/1.1 中也是如此。在这种情况下,它可能会在响应中返回 Connection: close 标头。这将正确地强制 Netty 关闭每个请求之间的连接,而不是重用它。
    
        
© www.soinside.com 2019 - 2024. All rights reserved.