【问题标题】:How can you close a tokio-postgres connection?如何关闭 tokio-postgres 连接?
【发布时间】:2021-07-13 14:05:15
【问题描述】:

在第一个例子的tokio-postgresdocumentation中,有一个例子表明你应该在一个单独的线程中运行数据库连接:

// 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);
    }
});

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

【问题讨论】:

  • "连接实现了Future,并且仅在连接关闭时才解决,要么是因为发生了致命错误,要么是因为其关联的客户端已丢失并且所有未完成的工作都已完成",因此连接会自动关闭当客户端被丢弃时。

标签: postgresql rust rust-tokio tokio-postgres


【解决方案1】:

如果你在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

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

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多