如何关闭 tokio-postgres 连接?

问题描述

在第一个示例的 tokio-postgres documentation 中,有一个示例表明您应该在单独的线程中运行数据库连接:

// The connection object performs the actual communication with the database,// so spawn it off to run on its own.
tokio::spawn(async move {
    if let Err(e) = connection.await {
        eprintln!("connection error: {}",e);
    }
});

如果你这样做了,你怎么能在之后终止那个连接?

解决方法

如果您在 tokio 1 上,tokio::task::JoinHandle 有一个 abort() 函数可以取消任务,从而断开连接。

let handle = task::spawn(async move {
    if let Err(e) = connection.await {
        eprintln!("connection error: {}",e);
    }
}
handle.abort(); // this kills the task and drops the connection

按原样使用我的代码段会立即终止任务,因此这可能不是您最终想要的,但是如果您保留 handle 并使用它,例如结合某种关闭侦听器,您应该能够根据需要控制连接。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...