【问题标题】:How do I solve the error "thread 'main' panicked at 'no current reactor'"?如何解决错误“线程'主'在'没有当前反应堆'时恐慌”?
【发布时间】:2020-04-22 05:50:38
【问题描述】:

我正在尝试连接到数据库:

extern crate tokio; // 0.2.6, features = ["full"]
extern crate tokio_postgres; // 0.5.1

use futures::executor;
use tokio_postgres::NoTls;

fn main() {
    let fut = async {
        let (client, connection) = match tokio_postgres::connect("actual stuff", NoTls).await {
            Ok((client, connection)) => (client, connection),
            Err(e) => panic!(e),
        };
        tokio::spawn(async move {
            if let Err(e) = connection.await {
                eprintln!("connection error: {}", e);
            }
        });

        let rows = match client
            .query(
                "SELECT $1 FROM planet_osm_point WHERE $1 IS NOT NULL LIMIT 100",
                &[&"name"],
            )
            .await
        {
            Ok(rows) => rows,
            Err(e) => panic!(e),
        };
        let names: &str = rows[0].get("name");
        println!("{:?}", names);
    };
    executor::block_on(fut);
    println!("Hello, world!");
}

它编译了,但是当我运行它时,我收到了错误消息

thread 'main' panicked at 'no current reactor'

【问题讨论】:

  • 难道不需要main函数上面的"#[tokio::main]"宏吗?

标签: rust future rust-tokio


【解决方案1】:

当使用许多(但不是全部)Tokio 功能时,您必须使用 Tokio reactor。在您的代码中,您尝试使用由期货箱 (executor::block_on) 提供的通用执行器。使用 Tokio 执行器和反应器通常通过使用 #[tokio::main] 宏来完成:

#[tokio::main]
async fn main() {
    let (client, connection) = match tokio_postgres::connect("actual stuff", NoTls).await {
        Ok((client, connection)) => (client, connection),
        Err(e) => panic!(e),
    };
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });

    let rows = match client
        .query(
            "SELECT $1 FROM planet_osm_point WHERE $1 IS NOT NULL LIMIT 100",
            &[&"name"],
        )
        .await
    {
        Ok(rows) => rows,
        Err(e) => panic!(e),
    };
    let names: &str = rows[0].get("name");
    println!("{:?}", names);
}

the tokio_postgres docs 中的第一个示例甚至向您展示了如何执行此操作:

#[tokio::main] // By default, tokio_postgres uses the tokio crate as its runtime.
async fn main() -> Result<(), Error> {

发生这种情况的一个原因是因为您使用的是tokio::spawn,而has this documented

如果从 Tokio 运行时外部调用,则会出现紧急情况。

另见:


这不会打印你想要的:

Err(e) => panic!(e),

你想要的

Err(e) => panic!("{}", e),

【讨论】:

  • [tokio::main] 到底做了什么我很困惑
  • @julia 这是一个宏。如果您展开宏,您可以确切地看到它的作用:How do I see the expanded macro code that's causing my compile error?
  • 如果我尝试使用 features 而不是 tokio 的功能,为什么我需要使用 Tokio reactor?
  • features 的一个功能”?我不知道你的意思。如果您的意思是期货,那么click the link to the related question 并使用block_on。如果您需要使用tokio::main,那么您(或依赖项)正在使用 Tokio 功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2022-01-25
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多