【问题标题】:Why do I get "panicked at 'not currently running on the Tokio runtime'" when using block_on from the futures crate?为什么我在使用期货箱中的 block_on 时会“对‘当前未在 Tokio 运行时运行’感到恐慌”?
【发布时间】:2020-01-16 04:36:55
【问题描述】:

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

【问题讨论】:

  • 你从哪里导入block_on函数?
  • 来自futures::executor::block_on

标签: rust rust-tokio


【解决方案1】:

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

【讨论】:

  • 这说明了很多。谢谢。
  • 使用第二种方法不编译,它给出了这两个错误:error[E0277]: main has invalid return type impl futures::Future --> src\main.rs:110:17 | 110 |异步 fn main() { | ^ main 只能返回实现Termination 的类型 | =帮助:考虑使用(),或Result错误[E0752]:main函数不允许为async --> src\main.rs:110:1 | 110 |异步 fn main() { | ^^^^^^^^^^^^^^^ main函数不允许为async
  • 请用你的真实代码和真实错误提出新问题,因为你要么没有使用与示例中完全相同的代码,要么没有显示你得到的完整错误。
【解决方案2】:

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

解决方案:

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


More about tokio compat

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多