Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

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

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.'.

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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...