在Go中关闭应用程序之前是否需要关闭数据库连接? [英] Do we need to close DB connection before closing application in Go?

查看:64
本文介绍了在Go中关闭应用程序之前是否需要关闭数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,当使用SQL数据库时,是否需要在关闭应用程序之前关闭数据库( db.Close )?数据库会自动检测到连接已终止吗?

In Go, when using a SQL database, does one need to close the DB (db.Close) before closing an application? Will the DB automatically detect that the connection has died?

推荐答案

DB会尽力检测,但是运气不好,它可能无法检测到.最好尽快发布所获得的东西.

DB will do its best to detect but with no luck, it may not be able to detect. Better to release what is acquired as soon as possible.

send()系统调用将等待TCP连接发送数据,但客户端不会收到任何信息.

send() system call will wait for TCP connection to send data but client won't receive anything.

  1. 发生电源故障,网络问题或裸机出口,但未正确释放资源.TCP keepalive机制将启动,并尝试检测到连接已死.

  1. Power failure, network issue or bare exit happened without properly releasing resources. TCP keepalive mechanism will kick in and try to detect that connection is dead.

客户端已暂停并且不接收任何数据,在这种情况下, send()将被阻止.

Client is paused and doesn't receive any data, in this case send() will block.

因此,它可能会阻止

  1. 正常关闭集群.
  2. 提高事件范围(如果它作为事务的一部分持有排他锁),例如postgresql中的 auto vacuum .

服务器的keepalive配置可以缩短以更早地检测到它.(例如,根据工作量,postgresql中的〜2h 12m 默认值会很长.)

Server keepalive config could be shortened to detect it earlier. (For example, ~2h 12m default in postgresql will be very long according to workload).

最大打开连接数可能有一个硬性限制,直到检测到之前,有些连接会变成僵尸(存在,无法使用,但会降低限制).

There may be a hard limit on max open connections, until detection, some connections will be zombie (there, unusable but decreases limit).

这篇关于在Go中关闭应用程序之前是否需要关闭数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆