如何将变量传递到并行异步 HTTP GET 请求中?

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

我对 Rust 编程非常陌生,我不明白如何将变量传递到这段代码中。我需要执行并行异步 HTTP GET 请求。我确实收到了这些字节,我希望根据 URL 将它们保存在 AAA、BBB、CCC 文件夹中。你能帮忙吗?

let mut urls:Vec<&str> = vec![];

    urls.push("url1?code=AAA");
    urls.push("url2?code=BBB");
    urls.push("url3?code=CCC");

    let client = Client::new();
    static mut CONTATORE : i32 = 0;

    let bodies = stream::iter(urls)
        .map(|url| {
            let client = client.clone();
            let codice = codice.clone();
            tokio::spawn(async move {
                let resp = client.get(url).header("Authorization", codice.clone()).send().await?;

                resp.bytes().await
            })
        })
        .buffered(PARALLEL_REQUESTS);

        
    bodies
        .for_each(|b| async {
            match b {
                Ok(Ok(b)) => {
                    println!("Got {} bytes", b.len());
                    //let my_string = String::from_utf8(b.to_vec()).unwrap();
                    //println!("{}", my_string);                    

                    let mut path: String = "data/esperimenti/".to_string();
//Variable CODE Should be here to save the specific bytes into a specific folder
                    path.push_str(&format!("{}", "CODE")); 
                    path.push_str(&format!("{}", ".json"));
                    
                    
                    
                },
                Ok(Err(e)) => eprintln!("Got a reqwest::Error: {}", e),
                Err(e) => eprintln!("Got a tokio::JoinError: {}", e),
            }
        })
        .await;

我尝试使用“不安全”的全局变量,但我不喜欢这个东西。

rust stream rust-tokio
1个回答
0
投票

您可以返回元组(或您的新类型),例如

resp.bytes().await
,而不是返回
(resp.bytes().await, "CODE".to_string())
,然后在
bodies.for_each()

中使用该返回类型
use futures; // 0.3.28
use tokio; // 1.29.1
use rand; // 0.8.5

use futures::stream::{StreamExt};

#[tokio::main]
async fn main()
{
    let bodies = futures::stream::iter(vec!["x".to_string(), "y".to_string(), "z".to_string()]).map(|v| {
        tokio::spawn(async move {
            (v, "CODE".to_string())
        })
    }).buffered(2);
    
    bodies.for_each(|v| async {
        if let Ok(v) = v {
            println!("{:?}", v);
        }
    }).await;
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0d35e00e18936673e133aa9f6b6872a7

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