From 7e2c4317c36fe649755b12b45e46994156821de9 Mon Sep 17 00:00:00 2001 From: asahi Date: Mon, 21 Apr 2025 12:42:42 +0800 Subject: [PATCH] =?UTF-8?q?doc:=20=E9=98=85=E8=AF=BBwebclient=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring/webflux/webclient.md | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 spring/webflux/webclient.md diff --git a/spring/webflux/webclient.md b/spring/webflux/webclient.md new file mode 100644 index 0000000..6f9a1ca --- /dev/null +++ b/spring/webflux/webclient.md @@ -0,0 +1,40 @@ +# WebClient +WebClient基于Reactor提供了`functional, fluent API`。 + +WebClient是非阻塞的,其依赖的codecs和server端使用的codecs相同。 + +## Configuration +创建`WebClient`最简单的方式是通过静态工厂方法: +- `WebClient.create()` +- `WebClient.create(String baseUrl)` + +除此之外,也可以通过`WebClient.builder()`来指定更多选项: +- `uriBuilderFactory`: 自定义uriBuilderFactory,用于创建UriBuilder,`UriBuilder`包含共享的配置,例如base URI等 +- `defaultUriVariables`: 在拓展uri templates时,使用到的默认值 +- `defaultHeader`:对每个请求都包含的headers +- `defaultCookie`:每个请求都包含的Cookie +- `defaultRequest`: 对每个请求进行自定义的`Consumer` +- `filter`:对于每个请求的client filter +- `exchangeStrategies`:自定义http message的reader/writer +- `clientConnector`:http client library设置 +- `observationRegistry`: the registry to use for enabling Observability support +- `observationConvention`: an optional, custom convention to extract metadata for recorded observations. + +创建WebClient的示例如下: +```java +WebClient client = WebClient.builder() + .codecs(configurer -> ... ) + .build(); +``` +一旦被创建后,WebClient是不可变的,`但是,可以对其进行克隆并对副本进行修改`,示例如下: +```java +WebClient client1 = WebClient.builder() + .filter(filterA).filter(filterB).build(); + +WebClient client2 = client1.mutate() + .filter(filterC).filter(filterD).build(); + +// client1 has filterA, filterB + +// client2 has filterA, filterB, filterC, filterD +```