使用请求上下文并行调用上游服务

时间:2021-01-29 08:27:32

标签: java reactive-programming spring-webflux spring-webclient

我是 Spring Web Flux 的新手。

我有一个不支持批量调用的上游服务,因此我必须为数组中的每个对象多次调用它。我还需要请求参数的实例,因为服务不会在其响应中返回这些属性。

例如, 这是我将发送给我们客户的回复

class Person {
  int id;
  String name;
  int phoneNo;
}

而且我只有 ID 列表

List<Integer> lstIds

对于每个人,api 响应也是

{
   "name": "name",
   "phoneNo": 2222222222
}

请注意,响应中没有 id 字段,因此我需要请求参数来将请求与响应进行映射。

我有一个名为 createRequestFromIdWillReturnMono(int id) 的方法,它接受整数 id 并返回 Web 客户端 Mono 作为响应。

到目前为止我尝试过的

List<Person> response = new ArrayList<Person>();
List<Integer> lstInt = IntStream.rangeClosed(0, 10).boxed().collect(Collectors.toList());
Flux
     .fromIterable(lstInt)
     .flatMap(i -> createRequestFromIdWillReturnMono(i)
                       .map(personResponse -> response.add(new Person(i, personResponse))));
return response; 

但是这段代码只运行了 response.add 调用一次,即使它调用了 createRequestFromIdWillReturnMono 10 次。

我应该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您不需要列表,您可以使用 collectList 并返回一个列表。或者您将 Flux<Person> 返回给客户端,这是一个流。

Mono<List<Persons>> personsMono = Flux.fromIterable(lstInt)
     .flatMap(i -> createRequestFromIdWillReturnMono(i))
     .map(personResponse -> new Person(i,personResponse))
     .collectList();

像这样的东西,我现在不在电脑上,所以不能确保它编译,但你应该明白。