微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Tokio 错误:即使安装了 #[tokio::main] 和单个版本的 tokio,“没有反应器在运行”

如何解决Tokio 错误:即使安装了 #[tokio::main] 和单个版本的 tokio,“没有反应器在运行”

当运行这样的代码时:

use futures::executor;
...
pub fn store_temporary_password(email: &str,password: &str) -> Result<(),Box<dyn Error>> {
  let client = DynamoDbClient::new(Region::ApSoutheast2);
  ...
  let future = client.put_item(input);
  executor::block_on(future)?; <- crashes here
  Ok(())
}

我收到错误

thread '<unnamed>' panicked at 'there is no reactor running,must be called from the context of a Tokio 1.x runtime

我的主要有 tokio 注释,因为它应该:

#[tokio::main]
async fn main() {
  ...

我的cargo.toml 看起来像:

[dependencies]
...
futures = { version="0",features=["executor"] }
tokio = "1"

我的cargo.lock 显示我只有1 个版本的futures 和tokio(分别为“1.2.0”和“0.3.12”)。

这用尽了我在别处找到的关于这个问题的解释。有任何想法吗?谢谢。

解决方法

您必须在调用 block_on 之前进入 tokio 运行时上下文:

let handle = tokio::runtime::Handle::current();
handle.enter();
executor::block_on(future)?;

请注意,您的代码违反了异步函数应该永远花费很长时间而不到达 .await 的规则。理想情况下,store_temporary_password 应标记为 async 以避免阻塞当前线程:

pub async fn store_temporary_password(email: &str,password: &str) -> Result<(),Box<dyn Error>> {
  ...
  let future = client.put_item(input);
  executor::block_on(future).await?;
  Ok(())
}

如果这不是一个选项,您应该将所有对 store_temporary_password 的调用包装在 tokio::spawn_blocking 中,以便在单独的线程池上运行阻塞操作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?