【问题标题】:How to create Spring WebClient from Apache Http Client如何从 Apache Http 客户端创建 Spring WebClient
【发布时间】:2019-01-16 20:08:14
【问题描述】:

我想从 HttpComponent 的 org.apache.http.client.HttpClient 创建 WebClient 以在异步操作中使用它。关于如何做的任何想法

【问题讨论】:

  • 我什至不知道你到底想要达到什么目的。到目前为止你做了什么?哪里出了问题?
  • 请提供更多详细信息
  • 嗨 Thomas 嗨 Sergey,我基本上有 http 客户端对象,需要创建一个 Web 客户端对象来进行异步调用,因为这仅支持反应式编程。无法找到一种方法那
  • Spring 目前支持 Jetty 和 Netty 客户端。见How to use Jetty client。基本上ClientHttpConnector 的任何实现都可以工作。目前 httpcomponent 的实现不可用 - 将来可能会添加。

标签: java spring-webflux apache-httpcomponents spring-webclient apache-httpclient-5.x


【解决方案1】:

随着 Spring Framework 5.3Spring Boot 2.4 的发布,现在 Apache HttpClient 5.0 和 Spring WebClient 之间已内置集成。

HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
clientBuilder.setDefaultRequestConfig(...);
CloseableHttpAsyncClient client = clientBuilder.build();
ClientHttpConnector connector = new HttpComponentsClientHttpConnector(client);

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

更新(基于@kolyaiks 的评论)

必要的依赖:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents.core5</groupId>
    <artifactId>httpcore5-reactive</artifactId>
    <version>5.1</version>
</dependency>

【讨论】:

  • 我想提一下,您必须添加一些 Maven 依赖项才能打开它:httpclient5httpcore5-parenthttpcore5-reactive
【解决方案2】:

使用 org.apache.http.client.HttpClient 很难,因为它不是为它设计的,你可以这样做,但这将是一个安静的、杂乱无章的解决方案,需要自己编写大量代码。 最好使用专为 HttpAsyncClient 设计的东西(也来自 apache btw。)

在这里您可以找到一些信息和代码示例: https://hc.apache.org/httpcomponents-asyncclient-ga/quickstart.html

祝你好运

【讨论】:

  • 如果我们没有使用 HttpAsyncClient 的选项,您能否分享一下可能是肮脏的解决方案,因为我们只有 HTTPClient 对象可用,而我们需要使用基于 Spring Webflux 的 WebClient 进行休息调用.
猜你喜欢
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
相关资源
最近更新 更多