使用spring,我想逐个发送WebFlux请求,直到响应满足特定的标准。我还需要收集所有的回复。在阻塞世界中,解决方案是这样的:
List<String> responses = new ArrayList<>();
String lastResponse;
do {
lastResponse = webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(String.class)
.block();
responses.add(lastResponse);
} while(!finished(lastResponse));如何在不阻塞的情况下实现这一点?
注意:有一个简单的递归解决方案,但我正在寻找一种更优雅的方法:
private List<String> collectRemaining() {
return webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(String.class)
.flatMap(response -> {
if(finished(response)) {
return List.of(response);
}
return collectRemaining().flatMap(remaining ->
Stream.concat(Stream.of(response), remaining.stream()).collect(Collectors.toList());
});
}发布于 2021-02-11 04:04:55
要替换递归,您可以使用expand()运算符,这使得可以根据前一个元素生成下一个元素。它通常用于实现分页逻辑。因此,下面这样的代码可能会起作用:
webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(String.class)
.expand(response -> {
if (finished(response)) {
return Mono.empty();
}
return webClient.get()
.uri(uri)
.retrieve()
.bodyToMono(String.class);
}).collectList();灵感来自this article。
https://stackoverflow.com/questions/66133897
复制相似问题