代码之家  ›  专栏  ›  技术社区  ›  alagner

在tokio任务之间共享reqwest::客户端

  •  0
  • alagner  · 技术社区  · 2 年前

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

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

    1. 包裹 客户 在里面 尽管如此,例如。
    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. 以其他方式缓解终身问题,只获取参考?(这里也欢迎任何提示)
    1 回复  |  直到 2 年前
        1
  •  1
  •   Chayim Friedman    2 年前

    …但我没有注意到 .clone() 返回浅副本:)

    但这正是你引用的医生所说的:

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

    推荐文章