【问题标题】:Spring 5 webflux how to set a timeout to an existing WebclientSpring 5 webflux 如何为现有的 Webclient 设置超时
【发布时间】:2019-11-23 10:35:31
【问题描述】:

我在我的配置类中定义了一个 WebClient bean。它涉及到对其连接器的大量配置(包括设置 SSL、代理等)。

    @Bean
    @Primary
    @Scope("prototype")
    public WebClient webClient()
    {
       SslContextBuilder builder = SslContextBuilder.forClient();
        HttpClient httpClient = HttpClient
                .create(ConnectionProvider.fixed("webClientPool", maxConnections))
                ...

        ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
        WebClient webClient = WebClient.builder()
                .clientConnector(connector)
                .exchangeStrategies(getExchangeStrategies())
                .build();
        return webClient;

在注入此 WebClient 的 bean 中,我想设置不同的超时。

我想使用webClient.mutate().clientConnector(...) 方法,但这需要我从头开始设置整个配置,只是为了设置超时。 不幸的是,WebClient 和 HttpClient 没有 .getxxx() 方法可以帮助我将旧的客户端配置复制到新的配置中。

我希望有一种方法可以只为变异的 WebClient 设置 tcp-client 的超时选项。 有办法吗?

【问题讨论】:

    标签: java spring spring-webflux reactor reactor-netty


    【解决方案1】:

    根据文档

    WebClient.Builder mutate()

    返回一个构建器以创建一个新的 WebClient,其设置是从当前 WebClient 复制的。

    将返回具有所有先前设置的新构建器,因此您无需复制任何内容。

    webclient mutate

    如果您想尽可能减少配置,您可以:

    定义一个@Bean,在其中尽可能多地配置HttpClient.Builder,以便稍后在HttpClient.Builder中自动装配

    然后你定义了 2 个 webclients,它们在 httpclient 中自动装配并完成 httpclient.build() 到每个 webclient 中。

    或者您定义一个 webclient,然后在需要修改的类中注入您在 webclient 和 httpclient.builder 中并完成配置并改变 webclient。

    【讨论】:

    • 谢谢。我已经想到了这个技术方案,但是我想避免这个多余的 Builder bean 并找到一个更优雅的解决方案,只依赖 WebClient bean。
    • 那么请定义什么是“优雅”,而不是因为“品味”而拒绝人们的回答。这是最优雅的解决方案恕我直言。
    • WebClient 构造使用HttpClient 对象,它使用.tcpConfiguration() 调用,它使用Function<TcpClient, TcpClient> 消费者。在我们的项目中,这个消费者配置了 tcp 客户端的超时时间和其他值。根据您的目标解决方案,我们需要再添加 2 个 bean:用于消费者和 HttpClient。然后我们必须注入这 3 个 bean,修改消费者,构建 HttpClient,用 ReactorClientHttpConnector 包装它并使用 WebClient.mutate().clientConnector(...) 设置它。
    • 我希望拥有的是:Function<...> tcpConfigSetter = webClient.clientConnector().httpClient().tcpConfiguration(); /* set new timeouts for the tcpConfig here */ webClient = webClient.mutate() .clientConnector() .httpClient() .tcpConfiguration(tcpConfigSetter);
    • 你自己也看到了,tcpConfiguration是一个函数,需要重新定义整个函数。所以你在问一个你已经知道答案的问题,并且你已经决定,这是唯一的解决方案。所以我只能说,祝你好运!
    猜你喜欢
    • 2018-02-24
    • 2018-08-06
    • 2018-06-14
    • 2019-04-13
    • 2022-09-23
    • 2021-08-13
    • 2018-05-09
    • 2017-12-31
    • 2019-05-04
    相关资源
    最近更新 更多