[英]Can I have blocking remote call in Flux.generate state generator
I am generating a Flux from a series of blocking REST API calls, each call depends on the result of previous call.我正在从一系列阻塞的 REST API 调用中生成 Flux,每次调用都取决于上一次调用的结果。 ie
IE
Result r1 = call(fromRow = 0);
Result r2 = call(fromRow = 0 + r1.size());
Result r3 = call(fromRow = 0 + r1.size() + r2.size());
...
Here is a simplified version of what I am trying with:这是我正在尝试的简化版本:
Flux.generate(() -> 0, (i, sink) -> {
Result r = slowRemoteCall(i);
if (r == null) {
sink.complete();
} else {
sink.next(r)
}
return i + r.size();
}, state -> {});
Just wonder will the blocking call slowRemoteCall
inside the state generator become a problem?只是想知道状态生成器内部的阻塞调用
slowRemoteCall
会成为问题吗?
Thank you for your help in advance!提前谢谢你的帮助!
With expand
operator and a reactive remote client (eg: Spring WebClient) you can implement this in a reactive non-blocking way:使用
expand
运算符和反应式远程客户端(例如:Spring WebClient),您可以以反应式非阻塞方式实现:
slowRemoteCall(0)
.expand(result -> {
if (result.size() == 0) { // stop condition
return Mono.empty();
} else {
return slowRemoteCall(result.startIndex() + result.size()); // maintain state
}
})
Mono<Result> slowRemoteCall(int startIndex) {
// simulate latency (could be a WebClient call here)
return Mono.delay(Duration.ofMillis(200)).thenReturn(new Result(startIndex));
}
Inspired by this blog post .灵感来自这篇博文。
It may become a problem!它可能会成为一个问题! If you have any blocking call, you can use
schedulers
to get the task done by specific thread pools.如果您有任何阻塞调用,您可以使用
schedulers
来让特定线程池完成任务。
Flux.generate(.........)
.subscribeOn(Schedulers.boundedElastic())
More info:更多信息:
https://www.vinsguru.com/reactive-programming-schedulers/ https://www.vinsguru.com/reactive-programming-schedulers/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.