在Tokio任务间共享reqwest::Client的正确方式
关于reqwest::Client在多Tokio任务中的复用方案选择
我需要启动多个Tokio任务来调用各类Web API,打算用reqwest::Client实现。
根据reqwest::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`
因此想咨询以下哪种方案更合适:
方案1:用Arc包装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(()) }
方案2:直接克隆Client
示例代码:
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()返回的是浅拷贝
方案3:通过其他方式解决生命周期问题并直接传递引用?(欢迎提供相关提示)
内容的提问来源于stack exchange,提问作者alagner
相关产品推荐
相关产品推荐

