我需要进行异步调用并使用其中存在的一些值对同一服务进行多次调用。将这些调用的响应与第一个调用组合并返回。
例如,当我第一次调用时,我得到下面的 JSON,它有一个 id 列表。现在,我必须使用这些 id 对服务进行多次调用,并列出它们的响应,并通过将其附加到相同的 JSON 中将其发送到下游。
{“id”: 145,
“object”:[{“id”:111}]
}
我试过使用 zipWhen 和
Flux.fromIterable(userIds).parallel().runOn(Schedulers.elastic()).flatMap()
但结果列表始终为空或 null。我们怎样才能做到这一点?我在这里错过了什么吗?
Edit1:通过使用解决它Flux.fromIterable
。阅读更多关于它的内容,最终了解了它的用途并解决了它。下面的方法从列表中取出一项,并调用内部方法,该方法将调用多个 API:
return Flux.fromIterable(somelist).flatMap(listItem -> {
return someMethodToCallAnotherAPIUsingZipWith(listItem);
}).collectList();
内部方法:它调用第一个 API,将其结果传递给 zipWith 并使用此结果我们可以调用另一个 API,或者我们可以简单地将其与响应一起使用。
private Mono<Object> someMethodToCallAnotherAPIUsingZipWith(String listItem) {
return authService.getAccessToken().flatMap(accessToken ->
webClient.get().uri(builder -> builder.path("/path").build(listItem))
.header(HttpHeaders.AUTHORIZATION, accessToken)
.retrieve()
.toEntity(Entity.class).log()
.flatMap(entity -> {
//manipulate your response or create new object using it
return Mono.just(entity);
}).zipWhen(consent -> webClient.get().uri(builder -> builder.path("/otherpath").build(listItem))
.header(HttpHeaders.AUTHORIZATION, accessToken)
.retrieve().bodyToMono(Entity.class).log()
.flatMap(entity -> {
//example
listItem = entity.getString();
return Mono.just(listItem);
}), (string1, string2) -> string1 + string2));
}