doukangbin9698 2018-08-15 12:25
浏览 66

如何安全地丢弃golang数据库/ sql池连接,例如当它们指向只读副本时?

We have been using golang's database/sql and github.com/lib/pq with a PostgreSQL cluster, meaning that a certain database server that was a replication master might be a read-only replica after the previous master has failed.

Recently, our low-usage service managed to keep a single connection in its connection pool (there were no concurrent requests that would have opened a second connection), and its target had been demoted to a read-only replica. As a result, each write operation to the service failed until it was restarted. That would not have happened, if a new connection was made to the cluster.

The problem is I can't find a documented way to discard a connection on certain kinds of errors. The only public method in database/sql that sounds correct is Conn.Close which returns the connection to the pool without closing it. Not calling it will cause a resource leak which will eventually make the pool unusable. Is there a sustainable way to get rid of a connection when the application wants to?

  • 写回答

2条回答 默认 最新

  • dpvp56187 2018-08-15 13:13
    关注

    I believe that when using database/sql, the answer is "no", though I'd be happy to be corrected.

    A while back, we switched from database/sql with lib/pq to the pure Go jackc/pgx for similar reasons (the inability to control connections on a low level), and were happy with the result. That module offers ConnPool.Reset which sounds like what you want here:

    Reset closes all open connections, but leaves the pool open. It is intended for use when an error is detected that would disrupt all connections (such as a network interruption or a server state change).

    It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned to the pool.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大