为什么我会“对‘当前未在 Tokio 运行时上运行’感到恐慌"?当使用期货箱中的 block_on 时? [英] Why do I get "panicked at 'not currently running on the Tokio runtime'" when using block_on from the futures crate?

查看:76
本文介绍了为什么我会“对‘当前未在 Tokio 运行时上运行’感到恐慌"?当使用期货箱中的 block_on 时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用有关他们的新板条箱的弹性搜索博客文章中的示例代码,但我无法让它按预期工作.线程恐慌,线程main"因当前未在 Tokio 运行时上运行"而恐慌..

I'm using the example code on elastic search's blog post about their new crate and I'm unable to get it working as intended. The thread panics with thread 'main' panicked at 'not currently running on the Tokio runtime.'.

什么是 Tokio 运行时,我如何配置它以及为什么必须我?

What is the Tokio runtime, how do I configure it and why must I?

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 在内部,因此您也必须使用它来匹配他们的假设.

It looks like Elasticsearch's crate is using Tokio internally, so you must use it too to match their assumptions.

在他们的文档中寻找 block_on 函数,我有 这个.所以,你的 main 看起来应该是这样的:

Looking for block_on function in their documentation, I've got this. So, it appears that your main should look like this:

use tokio::runtime::Runtime;

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

或者你可以让你的 main 函数本身与 属性宏,它将为您生成运行时创建和block_on调用:

Or you can make you main function itself async with the attribute macro, which will generate runtime creation and block_on call for you:

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

这篇关于为什么我会“对‘当前未在 Tokio 运行时上运行’感到恐慌"?当使用期货箱中的 block_on 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆