如何解决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 举报,一经查实,本站将立刻删除。