doc: 阅读webclient文档

This commit is contained in:
asahi
2025-06-03 23:27:54 +08:00
parent db56eddf84
commit 89f8bd9db4
2 changed files with 55 additions and 0 deletions

View File

@@ -469,6 +469,55 @@ client.get().uri("https://example.org/")
```
除此之外,可以通过`org.springframework.web.reactive.function.client.DefaultWebClientBuilder#defaultRequest`方法为`webClient`注册一个callback回调该回调可为所有请求插入attribute。
## Context
通过attribute可以便捷的向filter chain传递细信息。但是`attribute`针对的范围是`当前请求`
如果想要在`subscription`的范围内例如flatMap或concatMap等可以使用`Reactor Context`
使用示例如下所示:
```java
WebClient client = WebClient.builder()
.filter((request, next) ->
Mono.deferContextual(contextView -> {
String value = contextView.get("foo");
// ...
}))
.build();
client.get().uri("https://example.org/")
.retrieve()
.bodyToMono(String.class)
.flatMap(body -> {
// perform nested request (context propagates automatically)...
})
.contextWrite(context -> context.put("foo", ...));
```
## Synchronous Use
webclient同样支持同步使用示例如下
```java
Person person = client.get().uri("/person/{id}", i).retrieve()
.bodyToMono(Person.class)
.block();
List<Person> persons = client.get().uri("/persons").retrieve()
.bodyToFlux(Person.class)
.collectList()
.block();
```
对多个`Publisher`的操作进行zip的示例如下
```java
Mono<Person> personMono = client.get().uri("/person/{id}", personId)
.retrieve().bodyToMono(Person.class);
Mono<List<Hobby>> hobbiesMono = client.get().uri("/person/{id}/hobbies", personId)
.retrieve().bodyToFlux(Hobby.class).collectList();
Map<String, Object> data = Mono.zip(personMono, hobbiesMono, (person, hobbies) -> {
Map<String, String> map = new LinkedHashMap<>();
map.put("person", person);
map.put("hobbies", hobbies);
return map;
})
.block();
```