由于我的基本 URI 不固定,在 Webflux 中一次又一次地创建 Webclient 是不是明智?

Posted

技术标签:

【中文标题】由于我的基本 URI 不固定,在 Webflux 中一次又一次地创建 Webclient 是不是明智?【英文标题】:Is it wise to create Webclient again and again in Webflux since my base URI is not fixed?由于我的基本 URI 不固定,在 Webflux 中一次又一次地创建 Webclient 是否明智? 【发布时间】:2019-05-19 13:00:27 【问题描述】:

在我的微服务中,我必须从一些地方获取数据。有些 URL 是固定的,但有些不是。如果我的基本 URL 发生变化,我是否需要一次又一次地创建 Webclient。 如果不是,那么以下创建 Web 客户端的方法是否正确。 WebClient.create(); 然后每当我打电话时一次又一次地更改URI。 根据我的理解,创建 WebClient 必须是一些繁重的操作。

ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
                options -> options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, requestTimeout).compression(true)
                        .afterNettyContextInit(ctx ->  ctx.addHandlerLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS))));
        return WebClient.builder()
                        .clientConnector(connector)
                        .baseUrl(hostURL)
                        .build();

【问题讨论】:

有答案***.com/a/49107545/10264430 感谢@AlexanderPankin 但是在这里发布后找到了它:) Right way to use Spring WebClient in multi-thread environment的可能重复 @BrianClozel 我的问题有点不同。我的基本 URI 大部分时间都会发生变化。在这种情况下,提供的解释仍然有效。 我正在为每个请求创建 ReactorClientHttpConnector。并将其传递给 WebClient.create().clientConnector(ReactorClientHttpConnector ).baseURL("new URL").build() 【参考方案1】:

WebClient 实例是可重用的。您需要不同客户端实例的唯一原因是满足特定需求:可观察性检测、特定身份验证客户端过滤器、特定连接/读/写超时。

不同的基本 URI 并不是创建不同实例的重要理由。创建实例而不设置基本 URI 完全没问题,这只是为了在一遍又一遍地调用同一主机时避免重复。

这很好:

WebClient webClient = WebClient.builder().build();

Mono<Resource> resource = webClient.get().uri("http://example.org/resource").retrieve()...;
Mono<Project> project = webClient.get().uri("http://spring.io/projects/spring-boot").retrieve()...;

请注意,如果您使用 Spring Boot,则应考虑使用提供的 WebClient.Builder 构建您的 webclient 实例(请参阅 the Spring Boot reference documentation)。

【讨论】:

所以唯一要记住的是,如果我要控制 HTttpConnector,那么我需要在整个应用程序中使用相同的实例 你可以设置它我在 webclient builder 上就像在你的示例中一样。

以上是关于由于我的基本 URI 不固定,在 Webflux 中一次又一次地创建 Webclient 是不是明智?的主要内容,如果未能解决你的问题,请参考以下文章

WebFlux系列WebClient Uri列表数组传参

[转]springboot2 webflux 响应式编程学习路径

具有固定 URI 的 ASP.NET 路由不映射查询字符串参数

Webflux 并行连接以某种方式限制为 256

带有 Spring 安全 webflux 的 Angular 6 被 CORS 阻止

spring 5 webflux 功能端点请求中不存在访问控制源头