You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:30:15