http - 如何在不等待的情况下发送请求?

标签 http rust async-await reqwest

我正在使用 reqwest,并尝试每 97 毫秒发送一个请求。但是,我不想等待最后一个请求发生或读取它。

我只想每 97 毫秒发送一次请求,并始终将输出发送到 stdout。

我的(当前)代码是这样的:(keys 是一个带有 api 键的数组)

    loop {
    for i in keys.iter() {
        let url = format!("https://api.[insertsite].com/blahblah&apiKey={}", i);
        let res = client
            .get(url)
            .send()
            .await?
            .text()
            .await?;

        sleep(Duration::from_millis(97)).await;

        println!("{:?}", res);
        }
}

如果我删除等待,编译器会告诉我错误[E0599]:在当前范围内没有为不透明类型“impl std::future::Future”找到名为“text”的方法

TL;DR:我想每 97 毫秒发送一次 get 请求,无论有任何响应。如果/当有一个响应管道响应标准输出。

编辑:

我尝试使用线程,但我真的不知道如何使用。这是我想到的:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let keys = ["key", "key", "key"];
    let client = reqwest::Client::builder()
        .build()?;
    for i in keys.iter() {
        tokio::spawn(async move {
            let url = format!("https://api[insertsite].com/blahblah&apiKey={}", i);
            let res = client
                .get(url)
                .send()
                .await
                .text()
                .await;
             println!("{:?}", res);
             });
            sleep(Duration::from_millis(97)).await;
}
}

尝试运行时出现此错误:

error[E0599]: no method named `text` found for enum `std::result::Result<reqwest::Response, reqwest::Error>` in the current scope
  --> src/main.rs:22:18
   |
22 |                 .text()
   |                  ^^^^ method not found in `std::result::Result<reqwest::Response, reqwest::Error>`

最佳答案

您已经发现 tokio::spawn是完成此任务的正确工具,因为您本质上希望以“即发即忘”的方式使用一些异步代码,而不是在主程序流中等待它。您只需要对代码进行一些调整。

首先,对于您引用的错误 - 这是由于您必须以某种方式处理请求期间可能出现的错误。您只需在每个 await 之后添加问号即可返回Result ,但随后您会遇到以下情况:

error[E0277]: the `?` operator can only be used in an async block that returns `Result` or `Option` (or another type that implements `Try`)
  --> src/main.rs:11:23
   |
9  |           tokio::spawn(async move {
   |  _________________________________-
10 | |             let url = format!("https://api[insertsite].com/blahblah&apiKey={}", i);
11 | |             let res = client.get(url).send().await?.text().await?;
   | |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in an async block that returns `()`
12 | |             println!("{:?}", res);
13 | |         });
   | |_________- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `Try` is not implemented for `()`
   = note: required by `from_error`

“这个函数”位可能有点误导,因为错误的其余部分正在谈论“异步 block ”,但要点很简单:如果您使用问号将错误从某个地方冒出来,那么幸福的路径必须返回Result , 也。好吧,我们简单地添加 Ok(())到异步 block 的末尾,这是下一个错误:

error[E0282]: type annotations needed
  --> src/main.rs:11:51
   |
11 |             let res = client.get(url).send().await?.text().await?;
   |                                                   ^ cannot infer type of error for `?` operator
   |
   = note: `?` implicitly converts the error value into a type implementing `From<reqwest::Error>`

这也是预期的 - 在普通函数中返回类型将由其签名提供,但在异步 block 中这不是一个选项。但是,我们可以使用涡轮鱼:

tokio::spawn(async move {
    // snip
    Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
});

请注意,我们需要 SendSync :前者对于生成的错误能够跨越异步 block 边界是必要的,后者是因为 Box<dyn Error + Send> can't be created with From/Into conversion from other errors .


现在,我们还剩下两个编译错误,与之前的错误无关:

error[E0597]: `keys` does not live long enough
  --> src/main.rs:8:14
   |
8  |     for i in keys.iter() {
   |              ^^^^
   |              |
   |              borrowed value does not live long enough
   |              cast requires that `keys` is borrowed for `'static`
...
18 | }
   | - `keys` dropped here while still borrowed

error[E0382]: use of moved value: `client`
  --> src/main.rs:9:33
   |
7  |       let client = reqwest::Client::builder().build()?;
   |           ------ move occurs because `client` has type `reqwest::Client`, which does not implement the `Copy` trait
8  |       for i in keys.iter() {
9  |           tokio::spawn(async move {
   |  _________________________________^
10 | |             let url = format!("https://api[insertsite].com/blahblah&apiKey={}", i);
11 | |             let res = client.get(url).send().await?.text().await?;
   | |                       ------ use occurs due to use in generator
12 | |             println!("{:?}", res);
13 | |             Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
14 | |         });
   | |_________^ value moved here, in previous iteration of loop

第一个问题可以通过三种可能的方式修复:

  • 使用Vec安装数组并删除 .iter() ,
  • 使用std::array::IntoIter ,
  • 使用.iter().copied() 。 在每种情况下,我们都会得到 &'static str ,可以传递到异步 block 中。

第二个更简单:我们可以简单地执行let client = client.clone();在每次迭代开始时,tokio::spawn之前。这很便宜,因为 Client uses Arc internally .

这是playground ,进行上述所有更改。


最后,这是我个人建议您的代码所基于的版本,因为它不仅可以编译,而且不会消除根据请求可能出现的错误:

use core::time::Duration;
use tokio::time::sleep;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let keys = ["key", "key", "key"];
    let client = reqwest::Client::builder().build()?;

    for i in std::array::IntoIter::new(keys) {
        let client = client.clone();
        tokio::spawn(async move {
            let url = format!("https://api[insertsite].com/blahblah&apiKey={}", i);
            // moved actual request into inner block...
            match async move {
                let res = client.get(url).send().await?.text().await?;
                // ...returning Result with explicit error type,
                // so that the wholeinner async block is treated as "try"-block...
                Ok::<_, Box<dyn std::error::Error + Send + Sync>>(res)
            }
            .await
            {
                // ...and matching on the result, to have either text or error
                // (here it'll always be error, due to invalid URL)
                Ok(res) => println!("{:?}", res),
                Err(er) => println!("{}", er),
            }
        });
        sleep(Duration::from_millis(97)).await;
    }

    // just to wait for responses
    sleep(Duration::from_millis(1000)).await;
    Ok(())
}

Playground

关于http - 如何在不等待的情况下发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67944699/

相关文章:

rust - 如何将许多参数传递给 rust actix_web 路由

c# - 启动后台任务并立即返回

javascript - typescript 2.1 with async/await 为 angularjs 生成 ES5/ES3 目标

vb.net - 异步等待超时

google-chrome - Web浏览器如何监控当前打开网页的网络?

python - 当新请求来自同一 session 中的同一用户时如何取消先前的请求

http - urllib3 - 无法设置 http 代理

javascript - 在angularjs中为这个HTTP GET添加HTTP基本认证

templates - C++ for Rust 中特定模板用法的等价物

types - 在包含 nalgebra 的 VectorN 类型的结构上派生 Copy 时出错