java - 如何在响应式范式中处理另一个休息服务时调用休息服务?
问题描述
我正在尝试围绕响应式编程和 spring webflux 库,所以我想先用 WebClient 尝试一些东西,所以我找到了 RESTful pokemon api ( https://pokeapi.co/ ) 并开始使用它,但是我在尝试从我调用的第一个服务返回的信息中调用第二个休息服务时遇到了一些麻烦,因为我没有从嵌套调用中得到任何结果
我一直在阅读反应器库并四处寻找可以帮助我满足我需要的操作员,但我一定是缺少或误解了某些东西,因为即使它看起来很常见,我也找不到示例,我我试图使用flatMap
将我的对象包裹在一个单一的Mono
中,并使用其他运算符来打印信息,也尝试使用block()
但我得到了相同的结果。
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.val;
import reactor.core.publisher.Mono;
public class PokemonClient {
WebClient client = WebClient.create("https://pokeapi.co/api/v2/");
public void getPokemon() {
val result = client.get()
.uri("/pokemon/ditto")
.accept(MediaType.APPLICATION_JSON)
.exchange();
Mono<Species> pkmnMono = result.flatMap(response -> response.bodyToMono(Pokemon.class))
.map(pokemon -> pokemon.getSpecies());
Mono<Object> resultMono = pkmnMono.flatMap(species -> client.get().uri("/pokemon-species/132/")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.flatMap(response -> response.bodyToMono(Object.class)));
Object species = resultMono.block();
System.out.println(species);
}
}
Pokemon 和 Species 是我仅用于映射第一次调用的结果的 bean 类。
我知道client.get().uri("/pokemon-species/132/")
它不会根据第一次通话带来信息,而且我不应该使用Object
,但此时我只是想了解发生了什么,我原来的方法调用species.getUrl()
,
我希望它能够从中带回信息, /pokemon-species/132/
但我什么也没得到,当我尝试用它来打印它时pkmnMono.block()
,它可以正常工作
解决方案
推荐阅读
- angular - Stripe PaymentIntent Card如何实现?
- python - 如何用 Python 中的 pandas 或其他包绘制漂亮的彩色表格?
- sql-server - T-SQL:需要 Top N 才能始终返回 N 行,即使为 null 或空白
- pandas - 如何跳过具有不明确列的多个 CSV 文件中的重复标题并合并为一个大数据框
- maven - 如何在使用 maven-dependency-plugin 解压工件时重命名文件?
- java - 从android中的第一个数组中查找第二个数组中存在的元素的索引
- command-line - 使用 oc 命令行客户端实例化 OpenShift 服务目录模板
- arrays - 如何返回包含用户输入的数组数组?
- python - 使用python执行本地服务器后如何修复404错误
- xpath - xpath - 考虑内部元素按文本获取元素