使用期货箱中的 block_on 时,为什么我会“对'当前未在 Tokio 运行时上运行'感到恐慌”?

Mir*_*asi 18 rust rust-tokio

我正在使用关于他们的新板条箱的弹性搜索博客文章中的示例代码,但我无法让它按预期工作。线程恐慌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());
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 16

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

block_on在他们的文档中寻找功能,我得到了这个. 所以,看起来你main应该是这样的:

use tokio::runtime::Runtime;

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

或者,您可以使您自己的main功能与属性 macro异步,这将生成运行时创建并block_on为您调用:

#[tokio::main]
async fn main() {
    elastic_search_example().await;
}
Run Code Online (Sandbox Code Playgroud)


S.R*_*S.R 6

当我曾经tokio::run(从 tokio version = 0.1)使用tokio02内部使用(tokio version = 0.2)的crate 时,我遇到了同样的错误(在我的情况下它是 reqwest)。首先,我只是换std::future::Futurefutures01::future::Futurefutures03::compat。让它编译。运行后我得到了你的错误。

解决方案:

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


更多关于 tokio compat