我正在尝试连接到数据库:
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'
最佳答案
在使用许多(但不是全部)Tokio 功能时,您必须使用 Tokio reactor。在您的代码中,您尝试使用 future 箱 ( executor::block_on
) 提供的通用执行程序。使用 Tokio 执行器和 react 器通常是通过使用 #[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 :Panics if called from outside of the Tokio runtime.
也可以看看:
这不会打印您想要的内容:
Err(e) => panic!(e),
你要
Err(e) => panic!("{}", e),
关于rust - 如何解决错误 "thread ' main' paniced at 'no current reactor'”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582398/