[英]How to limit parallel execution in Spring-Webflux?
My rest client implementation is using Webflux from Project Reactor and is similar to the following:我的其余客户端实现使用来自 Project Reactor 的 Webflux,类似于以下内容:
Flux<Response1> request1(String uri) {
return webClient
.get()
.uri(uri)
.retrieve()
.bodyToMono(Responses1.class)
.map(r -> response1ToList(r))
.flatMapMany(Flux::fromIterable);
}
Flux<Response2> request2(Response1 response1) {
uri = f(response1);
return webClient
.get()
.uri(uri)
.retrieve
.bodyToMono(Responses2.class)
.map(r -> response1ToList(r))
.flatMapMany(Flux::fromIterable);
}
Flux<Response2> res2 = res1.flatMap(request2).subscribe();
The initial request (request1) returns a list of elements used to send a series of requests (request2).初始请求 (request1) 返回用于发送一系列请求 (request2) 的元素列表。
My problem is that the request2s are all sent in parallel which is too heavy for the server.我的问题是 request2s 都是并行发送的,这对服务器来说太重了。
Is there a way to limit the number of request2s executed at the same time?有没有办法限制同时执行的 request2s 的数量?
You can control the number of inner stream flatMap()
subscribes to by passing in a concurrency factor.您可以通过传入并发因子来控制内部流
flatMap()
订阅的数量。
Flux<Response1> request1(String uri) {
return webClient
.get()
.uri(uri)
.retrieve()
.bodyToMono(Responses1.class)
.map(r -> response1ToList(r))
.flatMapMany(Flux::fromIterable);
}
Flux<Response2> request2(Response1 response1) {
uri = f(response1);
return webClient
.get()
.uri(uri)
.retrieve
.bodyToMono(Responses2.class)
.map(r -> response1ToList(r))
.flatMapMany(Flux::fromIterable);
}
Flux<Response2> res2 = res1.flatMap(request2, concurrencyFactor).subscribe();
If you want to do it one-by-one, you can use a concatMap()
.如果您想一一进行,可以使用
concatMap()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.