为什么我在使用 futures crate 中的 block_on 时得到 "panicked at 'not currently running on the Tokio runtime'"?

Why do I get "panicked at 'not currently running on the Tokio runtime'" when using block_on from the futures crate?

我正在使用 elasticsearch 博客 post 上关于他们的新 crate 的示例代码,但我无法让它按预期工作。线程出现 thread 'main' panicked at 'not currently running on the Tokio runtime.'.

恐慌

什么是 Tokio 运行时,我该如何配置它,为什么必须这样?

use futures::executor::block_on;

async elastic_search_example() -> Result<(), Box<dyn Error>> {
    let index_response = client
        .index(IndexParts::IndexId("tweets", "1"))
        .body(json!({
            "user": "kimchy",
            "post_date": "2009-11-15T00:00:00Z",
            "message": "Trying out Elasticsearch, so far so good?"
        }))
        .refresh(Refresh::WaitFor)
        .send()
        .await?;
    if !index_response.status_code().is_success() {
        panic!("indexing document failed")
    }
    let index_response = client
        .index(IndexParts::IndexId("tweets", "2"))
        .body(json!({
            "user": "forloop",
            "post_date": "2020-01-08T00:00:00Z",
            "message": "Indexing with the rust client, yeah!"
        }))
        .refresh(Refresh::WaitFor)
        .send()
        .await?;
    if !index_response.status_code().is_success() {
        panic!("indexing document failed")
    }
}

fn main() {
    block_on(elastic_search_example());
}

看起来 Elasticsearch 的 crate 正在内部使用 Tokio,因此您也必须使用它来匹配他们的假设。

在他们的文档中寻找 block_on 函数,我找到了 this。所以,您的 main 看起来应该是这样的:

use tokio::runtime::Runtime;

fn main() {
    Runtime::new()
        .expect("Failed to create Tokio runtime")
        .block_on(elastic_search_example());
}

或者您可以使 main 函数本身与 attribute macro 异步,这将生成运行时创建并 block_on 为您调用:

#[tokio::main]
async fn main() {
    elastic_search_example().await;
}

当我使用内部使用 tokio02(tokio 版本 = 0.2)的板条箱 tokio::run(来自 tokio 版本 = 0.1)(在我的例子中是 reqwest)时,我遇到了同样的错误. 首先,我只是将 std::future::Future 更改为 futures01::future::Futurefutures03::compat。使其编译。在 运行 之后我得到了你的错误。

解决方案:

添加 tokio-compat 解决了我的问题。


More about tokio compat