我正在尝试生成几个tokio任务,这些任务应该是查询各种web API。我的计划是使用
reqwest::Client
为此。
根据
reqwest::Client
docs
这个
Client
在内部保存一个连接池,因此建议您创建一个并重用它。
你不必包装
客户
在
Rc
或
Arc
重用它,因为它已经使用了
弧
内部。
试图在通常的、预期的投诉中获取参考结果
'static
21 | let webapi1 = tokio::spawn(async {do_stuff(&webapi_client).await});
| ^^^^^^^^^^^-------------^^^^^^^^
| | |
| | `webapi_client` is borrowed here
| may outlive borrowed value `webapi_client`
因此,我的问题是,我是否应该
-
包裹
客户
在里面
弧
尽管如此,例如。
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()
返回浅副本:)
-
以其他方式缓解终身问题,只获取参考?(这里也欢迎任何提示)