在 tokio 任务之间共享 reqwest::Client

问题描述 投票:0回答:1

我正在尝试生成几个 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`

因此我的问题是我是否应该

  1. 仍然将
    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(())
}

  1. 只需克隆客户端:
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()
返回浅拷贝:)

  1. 通过其他方式缓解生命周期问题并获取参考? (也欢迎任何提示)
rust rust-tokio
1个回答
0
投票

...但我没有注意到

.clone()
返回浅拷贝:)

但这正是您引用的文档所说的:

您不必将 Client 包装在 Rc 或 Arc 中即可重用它,因为它已经在内部使用了

Arc

© www.soinside.com 2019 - 2024. All rights reserved.