Do we need to close DB connection before closing application in Go?

邮差的信 提交于 2021-02-07 13:52:02

问题


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?


回答1:


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() system call will wait for TCP connection to send data but client won't receive anything.

  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.

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

As a result, it may prevent

  1. Graceful shutdown of cluster.
  2. Advancing event horizon if it was holding exclusive locks as a part of transaction such as auto vacuum in postgresql.

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).




回答2:


The database will notice the connection had died and take appropriate actions: for instance, all uncommitted transactions active on that connection will be rolled back and the user session will be terminated.

But notice that this is a "recovery" scenario from the point of view of the database engine: it cannot just throw up when a client disconnects; it rather have to take explicit actions to have consistent state.

On the other hand, to shut down property when the program goes down "the normal way" (that is, not because of a panic or log.Fatal()) is really not that hard. And since the sql.DB instance is usually a program-wide global variable, its even simpler: just try closing it in main() like Matt suggested.




回答3:


If you're initialising a connection in any function, you're normally better off deferring the call to close immediately, i.e.

conn := sql.Connect() // for example
defer conn.Close()

Which will close the connection once the enclosing function exits.

This is handy when used in a main function since once the program exits, the call to Close() will happen.



来源:https://stackoverflow.com/questions/34175299/do-we-need-to-close-db-connection-before-closing-application-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!