WebClient

https://www.cnblogs.com/crazymakercircle/p/14361256.html#autoid-h3-5-2-0

WebClient 是什么

WebClient 是 Spring Web 模块中的一个非阻塞、响应式的 Web 客户端库。它支持异步和同步的请求,并且可以与任何 HTTP 客户端库集成。

WebClient 是一个基于 Reactor 的库,它使用 Reactor 的 MonoFlux 类型来处理异步请求和响应。

WebClient 使用 Reactor Netty 库作为默认的 HTTP 客户端,但也可以使用其他 HTTP 客户端库,Apache HttpComponents、OkHttp 等。可通过 ClientHttpConnector 接口实现自定义的 HTTP 客户端。

创建WebClient

WebClient webClient = WebClient.create("http://localhost:8080");
webClient.get().uri("/hello").retrieve().bodyToMono(String.class).subscribe(System.out::println);

还可以使用 WebClient.builder() 静态工厂方法创建 WebClient 实例。

WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();

WebClient.builder()的其他选项:

  • uriBuilderFactory: 用于创建 UriBuilder 实例的工厂

  • defaultHeader: 默认的请求头

  • defaultCookie: 默认的 Cookie

  • defaultUriVariables: 默认的 URI 变量

  • defaultRequest: 默认的请求配置

  • exchangeStrategies: 用于序列化和反序列化的策略

  • filter: 用于添加过滤器

  • clientConnector: 用于创建 ClientHttpConnector 实例的工厂

WebClient 实例克隆

一旦建立,WebClient 实例就是不可变的。如果需要修改 WebClient 实例的配置,可以通过克隆一个新的 WebClient 实例来实现。

WebClient webClient = WebClient.create("http://localhost:8080");
WebClient newWebClient = webClient.mutate().baseUrl("http://localhost:8081").build();

最后更新于

这有帮助吗?