SpringBoot WebFlux:解析并行WebClient请求

问题描述

我正在使用spring webclient并行调用API。 响应看起来像这样

{
  "d": {
    "results": [
        {
            "id": "1","name": "Test A"
        },{
            "id": "2","name": "Test B",}

    ]
  }
}

POJO:

public class ProductResponse {
    private Products d;
}

public class Products {
    private List<ProductModel> results;
}

public class Product {
    private String id;
    private String name;
}

API调用:

public Flux<ProductsResponse> getProducts(final List<String> pages) {
    return Flux.fromIterable(pages)
            .flatMap(page -> webClient.get().uri("SOMEURL?page={page}",page)
                    .accept(MediaType.APPLICATION_JSON)                        
                    .retrieve()
                    .bodyToMono(ProductsResponse.class))
            .log()
            .subscribeOn(Schedulers.elastic());
}

获取产品

Flux<ProductsResponse> productList = getProductList(pages);
List<ProductsResponse> productsResponse = productList.collectList().block();
for (ProductsResponse response : productsResponse) {
    for (ProductModel product: response.getD().getResults()) {
        System.out.println(product.getProductId());
    }
}

这也可以,但是有没有办法直接返回Flux<Product>,还是返回Mono<List<Product>>更好呢?

(下一步是将产品保存到数据库中)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)