19

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

2 回答 2

18

看起来 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());
}

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

#[tokio::main]
async fn main() {
    elastic_search_example().await;
}
于 2020-01-16T07:07:01.763 回答
7

当我曾经tokio::run(从 tokio 版本 = 0.1)使用在内部使用tokio02(tokio 版本 = 0.2)的板条箱(在我的情况下是 reqwest)时,我遇到了同样的错误。首先,我只是更改std::future::Futurefutures01::future::Futurewith futures03::compat。使其编译。运行后,我得到了你的错误。

解决方案:

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


更多关于 tokio compat

于 2020-03-25T16:49:49.943 回答