Spring Webflux:并行调用的竞赛,当其中一个响应包含数据时取消/返回

时间:2018-11-14 10:53:47

标签: spring spring-webflux

我对三个不同的端点进行了三个并行调用,并且其中只有一个将返回我要处理的数据(响应将仅具有enpoint-1,enpoint-2或endpoint-3的数据)。 如果其中一个调用返回了数据,我想立即返回该数据,而忽略其他调用...。如何使用Spring Webflux实现此目的?

我打了三个电话:

Mono<MyResponse> result = client.post()
  .uri('uri')
  .body(Mono.just(request), MyRequest.class)
  .retrieve()
  .bodyToMono(MyResponse.class);

已添加到Mono列表

 List<Mono<MyResponse>> calls

我合并了所有回复,然后寻找第一项:

Flux.merge(calls).toStream().forEach(response -> myResponseList.addAll(response));

但是我想在任何调用返回非null值后立即返回数据,而不是等待“合并”完成。

谢谢!

1 个答案:

答案 0 :(得分:0)

您只能使用助焊剂的第一个元素

 Flux.merge(calls).take(1)

您将获得仅具有第一个元素的新助焊剂,并在生产后完成。