问题描述
在第一个示例的 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
并使用它,例如结合某种关闭侦听器,您应该能够根据需要控制连接。