2

如何让 Rust 执行所有给定的期货(如join_all!)限制一次执行 10 个期货?

我需要从大量服务器下载文件,但同时查询不超过 10 个服务器(以准确测量它们的超时:如果我一次查询太多服务器,它们会超时,即使服务器本身速度很快)。

4

1 回答 1

3

您可以futures通过创建期货流(例如使用futures::stream::iter)并调用buffered或以并行buffer_unordered执行最多n 个期货来使用 crate 执行此操作。

use futures::prelude::*;

// create an iterator of futures to execute
let futures =
    (0..50).map(|n| async move {
        fetch(format!("https://server-{}.example.com", n)).await
    });

// create a buffered stream that will execute up to 10 futures in parallel
// (without preserving the order of the results)
let stream = futures::stream::iter(futures).buffer_unordered(10);

// wait for all futures to complete
let results = stream.collect::<Vec<_>>().await;

在操场上运行示例

于 2022-01-27T00:00:49.727 回答