我正在使用关于他们的新板条箱的弹性搜索博客文章中的示例代码,但我无法让它按预期工作。线程恐慌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)
当我曾经tokio::run
(从 tokio version = 0.1)使用tokio02
内部使用(tokio version = 0.2)的crate 时,我遇到了同样的错误(在我的情况下它是 reqwest)。首先,我只是换std::future::Future
到futures01::future::Future
与futures03::compat
。让它编译。运行后我得到了你的错误。
添加tokio-compat解决了我的问题。