About sql.DB
Several parameters can be optimized we look at the actual scene, configured properly, then it can enhance performance and reduce system resource consumption in the establishment and use of a database connection.
SetMaxOpenConns
For setting the maximum number of open connections, the default value is 0, not to limit.SetMaxIdleConns
For setting the number of connections idle, the default value is 2;SetConnMaxLifetime
Can limit the maximum duration of a connection, the default value is 0, not to limit.
SetMaxOpenConns
By default, the maximum number of connection pools is no limit. In general, the more connections, the higher the performance of the database. But the system resources are not unlimited, concurrent capacity of the database is not unlimited. Therefore, in order to reduce the risk of system crashes and the database, you can set an upper limit on the number of concurrent connections, this value is generally not exceed the maximum process number of open file handles, no more than the number of concurrent connections to the database itself support services, such as 1000.
SetMaxIdleConns
The higher upper limit is theoretically maxIdleConns connection, i.e. the greater the maximum allowed connection idle connection pool, which can effectively reduce the number of connection creation and destruction, improve the performance. But also the connection object memory resources, and if more idle connections, connection pool exists in time may be longer. 连接在经过一段时间后有可能会变得不可用
, And then connected to the connection pool is still not recovered, then the follow-up time was requisitioned will be a problem. General recommendations maxIdleConns value of MaxOpenConns 1/2
for reference purposes only.
SetConnMaxLifetime
Set the maximum time a connection is used, will be forced to recover after a period of time that is, in theory, it can effectively reduce the probability of occurrence of connection is not available. When the database is also provided a connection timeout, the timeout value should not exceed the value of the parameter database.
# 仅供参考,应当按实际测试效果为准
db.SetMaxOpenConns(1000)
db.SetMaxIdleConns(500)
db.SetConnMaxLifetime(10*time.Minute)