我正在尝试生成几个 tokio 任务,这些任务应该查询各种 Web API。我的计划是使用
reqwest::Client
来实现这一点。
reqwest::Client
文档
内部拥有一个连接池,因此建议您创建一个并重用它。 您不必将Client
包裹在Client
或Rc
中即可重复使用它,因为它内部已经使用了Arc
。Arc
试图在通常的、预期的抱怨中获取参考结果
'static
21 | let webapi1 = tokio::spawn(async {do_stuff(&webapi_client).await});
| ^^^^^^^^^^^-------------^^^^^^^^
| | |
| | `webapi_client` is borrowed here
| may outlive borrowed value `webapi_client`
因此我的问题是我是否应该
Client
包裹在 Arc
中,例如 use std::sync::Arc;
async fn do_stuff(client : Arc<reqwest::Client>) {
client.get("www.google.com").send().await;
}
#[tokio::main]
async fn main() -> tokio::io::Result<()> {
let webapi_shared = Arc::new(reqwest::Client::new());
let webapi_client = &*webapi_shared;
let webapi_for_f1 = webapi_shared.clone();
let webapi_for_f2 = webapi_shared.clone();
let webapi1 = tokio::spawn(async move{do_stuff(webapi_for_f1).await});
let webapi2 = tokio::spawn(async move{do_stuff(webapi_for_f2).await});
webapi_client.get("www.google.com").send().await;
webapi1.await;
webapi2.await;
Ok(())
}
use std::sync::Arc;
async fn do_stuff(client : reqwest::Client) {
client.get("www.google.com").send().await;
}
#[tokio::main]
async fn main() -> tokio::io::Result<()> {
let webapi_client = reqwest::Client::new();
let webapi_for_f1 = webapi_client.clone();
let webapi_for_f2 = webapi_client.clone();
let webapi1 = tokio::spawn(async move{do_stuff(webapi_for_f1).await});
let webapi2 = tokio::spawn(async move{do_stuff(webapi_for_f2).await});
webapi_client.get("www.google.com").send().await;
webapi1.await;
webapi2.await;
Ok(())
}
...但我没有注意到
.clone()
返回浅拷贝:)
...但我没有注意到
返回浅拷贝:).clone()
但这正是您引用的文档所说的:
您不必将 Client 包装在 Rc 或 Arc 中即可重用它,因为它已经在内部使用了
。Arc