问题
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.
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.
Client is paused and doesn't receive any data, in this case
send()
will block.
As a result, it may prevent
- Graceful shutdown of cluster.
- 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