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

时间:2021-06-12 00:38:02

标签: http rust async-await reqwest

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

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

我的(当前)代码是这样的:(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);
        }
}

如果我删除等待,编译器会告诉我 error[E0599]: no method named `text` found for opaque type `impl std::future::Future` in the current scope

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>`

1 个答案:

答案 0 :(得分:2)

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

首先,对于您引用的错误 - 这是因为您必须以某种方式处理请求期间可能出现的错误。您可以简单地在每个返回 awaitResult 后添加问号,但是您会遇到以下情况:

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`

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

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>`

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

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

请注意,我们需要 SendSync:前者对于产生的错误能够跨越异步块边界是必要的,而后者 - 因为 Box<dyn Error + Send> {{ 3}}。


现在,我们还有两个编译错误,独立于之前的错误:

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,它可以传递到异步块中。

第二个更简单:我们可以在每次迭代开始时,在 let client = client.clone(); 之前简单地执行 tokio::spawn。这很便宜,因为 can't be created with From/Into conversion from other errors

这是 Client uses Arc internally,包含上述所有更改。


最后,这是我个人推荐您的代码所基于的版本,因为它不仅可以编译,而且还不会吞下根据要求可能出现的错误:

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