postgresql - 如何在 tokio_postgres 中使用自定义 Tokio 运行时(并且没有 tokio::main 宏)?
问题描述
我将如何使用自定义 tokio 运行时构建器并且没有主宏来实现这个 tokio_postgres 示例?
根据 tokio_postgres文档,这很好用:
示例/withmacro.rs
use tokio_postgres::{NoTls, Error};
async fn db_main()-> Result<(), Error> {
// pasted from: https://docs.rs/tokio-postgres/0.6.0/tokio_postgres/index.html
// Connect to the database.
let conn_string = std::env::var("PG_CONNECT").unwrap();
let (client, connection) = tokio_postgres::connect(&conn_string,NoTls).await?;
// The connection object performs the actual communication
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
// Now we can execute a simple statement that just returns its parameter.
let rows = client
.query("SELECT $1::TEXT", &[&"hello world"])
.await?;
// And then check that we got back the same string we sent over.
let value: &str = rows[0].get(0);
println!("value: {:?}", &value);
assert_eq!(value, "hello world");
Ok(())
}
#[tokio::main]
async fn main() {
dotenv::dotenv().ok();
let _ = db_main().await;
}
但是,我想像下面的主要内容那样自定义 tokio 运行时构建器——而不是使用 tokio 宏。然而,当涉及到运行时的“tokio_postgres::connect”时,这会让人恐慌地说“没有反应器正在运行”。我应该如何重新配置以下代码以在 tokio_postgres 中使用我自己的 Tokio 运行时实例(假设这甚至是我需要的)?
示例/nomacro.rs
use tokio_postgres::{NoTls, Error};
async fn db_main()-> Result<(), Error> {
// Connect to the database.
let conn_string = std::env::var("PG_CONNECT").unwrap();
// This line panics with:
// "thread 'main' panicked at 'there is no reactor running, must be called from the context of Tokio runtime', /Users/me/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.3.2/src/io/driver/mod.rs:254:13"
let (client, connection) = tokio_postgres::connect(&conn_string, NoTls).await?;
// ...
Ok(())
}
fn main() {
dotenv::dotenv().ok();
// Tokio 0.3
let rt:Runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.thread_name("my thread")
.build()
.unwrap();
rt.block_on( async {
db_main().await;
});
}
我应该将运行时的引用传递db_main()
给 tokio_postgres 的实例Config
吗?我已经尝试在 Cargo.toml"tokio-postgres = { version = "0.6.0", default-features = false}"
中禁用 tokio_postgres 中的 tokio 实例。
基线 Cargo.toml:
[dependencies]
dotenv = "0.15.0"
tokio = { version = "0.3", features = ["rt-multi-thread", "macros"] }
tokio-postgres = { version = "0.6.0"}
# tokio-postgres = { version = "0.6.0", default-features = false}
解决方案
非常多的学习(rust,tokio,postgres),我被这个问题所暗示enable_io()
,我一时兴起尝试了一个可行的解决方案:
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.thread_name("my thread")
.enable_io()
.build()
.unwrap();
我很乐意听从东京那些更聪明的人的意见。这可能是一个不断发展的文档的案例。恐慌源于东京。虽然 Postgres 需要“io”很直观,但Tokio Builder、tokio_postgres的示例和下面的代码并未暗示需要enable_io()
Tokio builder 才能使 tokio_postgres 工作。如果我不质疑这是一个完全错误的方法,我会提出一个文档拉取请求。
cfg_rt! {
impl Handle {
/// Returns a handle to the current reactor
///
/// # Panics
///
/// This function panics if there is no current reactor set and `rt` feature
/// flag is not enabled.
pub(super) fn current() -> Self {
crate::runtime::context::io_handle()
.expect("there is no reactor running, must be called from the context of Tokio runtime")
}
}
}
推荐阅读
- flutter - Dart 中的字符串文字类型模拟
- angular - Primeng Carousel 没有得到正确的样式
- vba - 在 VBA 中引用查询以发送多封电子邮件
- html - why my page is not showing background color when i have added the css
- node.js - 在socket.io“connection”中使用express“app.get”中定义的变量
- azure-web-app-service - 从应用服务到 Azure Key Vault 的身份验证失败
- git - 获取修改后的新位置
- ios - SwiftUI 基于计算属性显示警报
- php - Opcache 使用的内存不会改变
- vue.js - 将“proposal-object-rest-spread”插件添加到 babel.config.js 以修复 Microsoft Edge 错误 SCRIPT1028