gpt4 book ai didi

angular - 如何使用最大并行请求数发送 1000 个 XHTTP 请求

转载 作者:行者123 更新时间:2023-12-04 13:13:10 25 4
gpt4 key购买 nike

我有一个 Angular 应用程序,它需要发送 N 个 XHTTP 请求,其中 1 <= N <= 10000。
应用程序需要尽可能快地处理它,所以最好同时有多个事件的 XHTTP 请求,同时有多个请求的滑动窗口。由于服务器端 API 限制,无法使用 WebSocket 或其他类似流的解决方案。
我的第一个想法是使用类似 RxJS forkJoin 的东西,但我很难限制并发请求数。据我所知,最大请求数有 API 限制,例如 Chrome will allow only 8 simultaneous要求。
大部分solutions/tutorials我发现 a.) 不限制最大并发连接数或 b.) 不动态更新(超时解决方案对于此任务效率不高)。
例如:

const test = () =>
request(`https://swapi.co/api/people/1/`)
.pipe(
delay(1000),
switchMap(response => from(response.films)),
concatMap((url: string) => request(url).pipe(delay(1000))),
scan((acc, res) => [...acc, res.title], []),
tap(console.log)
)
.subscribe()
对我不利,因为限制是通过延迟实现的,但我想实现类似基于线程的解决方案:并发连接数最多为 Y,如果一个连接完成,则立即启动新请求。
const test = () =>
request(`https://swapi.co/api/people/1/`)
.pipe{
switchMap(response => from(response.films)),
specialOperatorIAmLookingFor((url: string) => request(url), 8), // where '8' is the maximum number of paralell requests
scan((acc, res) => [...acc, res.title], []),
tap(console.log)
)
.subscribe()
任何想法如何很好地解决这个问题? RxJS 感觉应该有一个已经写好的解决方案。

最佳答案

你可以尝试使用 RxJS bufferCount concatMap 运营商以及 forkJoin() .
来自 bufferCount文档:

Collect emitted values until provided number is fulfilled, emit asarray.


所以它收集 n通知的数量并将其作为数组发出。然后我们可以通过 forkJoin() 传递数组为 n并行请求的数量。
尝试以下
我假设 this.urls是类似于 HTTP 请求的集合
urls = [
this.http.get('url1'),
this.http.get('url2'),
this.http.get('url3'),
...
];
然后请求触发代码看起来像
bufferedRequests() {
from(this.urls).pipe(
bufferCount(6), // <-- adjust number of parallel requests here
concatMap(buffer => forkJoin(buffer))
).subscribe(
res => console.log(res),
err => console.log(err),
() => console.log('complete')
);
}

根据 this Chromium 工程师的评论,最大的实际解决方案。连接到主机/域限制将使用 WebSockets 或域分片。但是由于您提到在您的环境中不可能,您可以使用缓冲请求解决方法。
但是我不会尝试缓冲到最大限制。如果您向同一个域发送的请求多于允许的最大值,您可以看到额外的请求实际上会延迟,直到上述请求完成。因此,如果要缓冲到最大允许限制,并且您的应用程序从应用程序工作流所依赖的其他地方向同一域发送额外请求,则整个应用程序可能会受到限制。
所以最好使用 WebSockets 或域分片。如果两者都不可能,最好将请求缓冲到小于*最大允许限制的请求数量。
* 显然,如果您 100% 确定在缓冲过程中不会向同一域触发其他请求,那么您可以缓冲到最大。允许的限度。

关于angular - 如何使用最大并行请求数发送 1000 个 XHTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62871599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com