首页 > 解决方案 > 如何在响应式范式中处理另一个休息服务时调用休息服务?

问题描述

我正在尝试围绕响应式编程和 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(),它可以正常工作

标签: javareactive-programmingspring-webfluxproject-reactor

解决方案


推荐阅读