GoLang里的DB连接池
[ 2015/11/03 18:01 | by ipaddr ]
GoLang的数据库类库,自带了DB连接池功能,官方文档有介绍:
https://golang.org/pkg/database/sql/#DB
DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.
The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can only be reliably observed within a transaction. Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.
可以通过SetMaxIdelConns, SetMaxOpenConns来限制DB的连接数。
GoLang自动进行连接池的管理,默认情况下没有连接数限制,同时没有连接可用的话会新建连接;所以代码中没有正确的释放连接将导致连接数不断增加,比如以下代码:
_, err := db.Query("SELECT uId FROM tUser WHERE userName='tomzhou'")
此代码,由于返回的Row未使用,所以此连接会一直占用不会释放;正确的做法:
rows, err := db.Query("SELECT uId FROM tUser WHERE userName='tomzhou'")
defer rows.Close()
//或在合适的地方主动关闭rows;