如何解决错误 "thread 'main' panicked at 'no current reactor'"?

How do I solve the error "thread 'main' panicked at 'no current reactor'"?

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

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  FROM planet_osm_point WHERE  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'

当使用许多(但不是全部)Tokio 功能时,您必须使用 Tokio reactor。在您的代码中,您正在尝试使用 futures crate (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  FROM planet_osm_point WHERE  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 which has this documented:

Panics if called from outside of the Tokio runtime.

另请参阅:


这不会打印您想要的内容:

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

你想要

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