微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在tokio_postgres中使用自定义的Tokio运行时并且没有tokio :: main宏?

如何解决如何在tokio_postgres中使用自定义的Tokio运行时并且没有tokio :: main宏?

如何使用自定义的tokio运行时构建器而不使用主宏来实现此tokio_postgres示例?

根据tokio_postgres docs,此方法工作正常:

examples / 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运行时实例(假设这甚至是我所需要的)?

examples / nomacro.rs

use tokio_postgres::{NoTls,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,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}

解决方法

非常多的学习(生锈,tokio,postgres),我被this issue引向enable_io(),我一时兴起地尝试了一个可行的解决方案:

let rt = tokio::runtime::Builder::new_multi_thread()
    .worker_threads(6)
    .thread_name("my thread")
    .enable_io()
    .build()
    .unwrap();

我很乐意服从那些在东京很聪明的人。可能是文档不断发展的情况。恐慌起源于here,始于Tokio。尽管通常认为Postgres需要“ io”,但Tokio Buildertokio_postgres和以下代码的示例并不暗示需要Tokio构建器上的enable_io()才能使tokio_postgres正常工作。如果我不怀疑这是一种完全错误的方法,那么我会提出文档拉取请求。

来自tokio/src/io/driver/mod.rs

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")
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?