← 中文资源

简体中文版本

Rust async/await 并发抓取

用 async 函数与 futures::join_all 并发执行多个抓取任务,并理解 await 的约束。

阅读英文原文

题目

编写 async Rust 函数,使用 tokio::join! 并发抓取多个 URL 并返回状态码。输入契约:多个 URL 字符串;输出契约:所有响应的 HTTP 状态码向量。公开样例两个 URL 期望 [200, 200]——参考实现用模拟抓取返回 200。隐藏测试覆盖空列表与单 URL。

解题思路

先为每个 URL 创建 future 并收集到 Vec,再用 join_all 一次性等待全部完成;future 在 await 前不会执行,join_all 让它们并发推进。每个 async 函数返回一个可被轮询的状态机。

参考实现要点

async fn fetch_status(url: &str) -> u16 模拟抓取返回 200;async fn fetch_all(urls: Vec<String>) -> Vec<u16> 用 urls.iter().map(|u| fetch_status(u)).collect() 得到 future 向量,再 futures::future::join_all(futures).await。需要 tokio 运行时与 futures crate。

常见错误

原文指出在非 async 函数里使用 .await 会编译失败,函数必须标记 async。另一个坑是逐个 await 而不是 join_all:顺序等待会让总耗时累加,失去并发意义;验证时可用带延迟的模拟抓取比较耗时。

验证方式

在 Cargo 项目中加入 tokio(启用宏与运行时)和 futures 依赖,用 #[tokio::main] 运行 fetch_all;断言样例返回 [200,200]、空输入返回 [],并观察两个模拟延迟任务的总耗时接近单个任务。

代码示例

use tokio;
async fn fetch_status(url: &str) -> u16 {
    // Simulated fetch
    200
}
async fn fetch_all(urls: Vec<String>) -> Vec<u16> {
    let futures: Vec<_> = urls.iter().map(|u| fetch_status(u)).collect();
    futures::future::join_all(futures).await
}