【问题标题】:Use Spring WebClient response in next API call?在下一个 API 调用中使用 Spring WebClient 响应?
【发布时间】:2021-02-10 12:15:40
【问题描述】:
我想在下一个 API 调用中使用 WebClient 响应。因此,在调用下一个 api 之前,从响应中提取一些字段并在下一个 api 调用中使用它们。有一种方法可以阻止 WebClient 响应并使用它。但是有没有什么方法可以做到不阻塞呢?所以我的代码是这样的
response = getUserByWebClient1(); // web client call 1
extract id from response
getRolesByUserId(id); // webclient call 2
【问题讨论】:
标签:
java
spring-boot
spring-webclient
【解决方案1】:
这不是特定于WebClient,而是反应类型的一般概念,这里是Reactor Flux 和Mono。
您可以使用the flatMap operator 来实现这一点。
// given UserService with a method "Mono<User> getCurrentUser()"
// and RolesService with a method "Mono<RoleDetails> getRolesForUser(Long userId)"
Mono<RolesDetails> roles = userService.getCurrentUser()
.flatMap(user -> rolesService.getRolesForUser(user.getId());