在第一个示例的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);
}
});如果你这样做了,你怎么能在之后终止这种连接呢?
发布于 2021-04-19 21:48:08
如果您使用的是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并使用它,例如结合某种关闭侦听器,您应该能够控制所需的连接。
https://stackoverflow.com/questions/67160923
复制相似问题