我正在try 使用Rust的Tokio和reqwest crate 重新实现以下Python代码
#!/usr/bin/env python3
import asyncio
import httpx
import time
async def async_req(url, client):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.54",
"Cookie": ""
}
response = await client.get(url, headers=headers, timeout=180)
print(response.status_code)
print(response.text)
async def main():
urls = ["http://localhost:5000/hello", "http://localhost:5000/world"]
start = time.time()
async with httpx.AsyncClient() as client:
tasks = [async_req(url, client) for url in urls]
await asyncio.gather(*tasks)
print(time.time()-start)
if __name__ == "__main__":
asyncio.run(main())
在Rust中实现的代码如下:
async fn async_req(
url: &str,
client: reqwest::Client,
) -> Result<reqwest::Response, Box<dyn std::error::Error>> {
let response = client
.get(url)
.timeout(std::time::Duration::from_secs(180))
.send()
.await?;
Ok(response)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let urls = vec![
"http://localhost:5000/hello",
"http://localhost:5000/world",
];
let mut handles = vec![];
let client = reqwest::Client::new();
for url in urls {
let handle = {
let client = client.clone();
async move { async_req(url, client).await }
};
handles.push(handle);
}
let mut responses = vec![];
for handle in handles {
responses.push(handle.await?);
}
for response in responses {
println!("{}", response.text().await?);
}
Ok(())
}
但是,该程序似乎没有像在Python中那样发出异步请求.
我已经try 使用ChatGPT、Google和Stack Overflow来寻找解决方案,但我还没有找到不产生错误的解决方案.Cargo.toml的配置如下,我使用的Rust编译器版本是1.72.1(d5c2e9c34,2023-09-13)
[package]
name = "reqwest_async_demo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = { version = "^0.11" }
tokio = { version = "^1", features = [ "full" ] }
如果有人能帮我澄清这个困惑,我将不胜感激,并欢迎任何回复.谢谢.