在[https://github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) 可以看到关于go的连接池和超时相关的信息如下:
Connection pool and timeouts
The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see ***DB.SetMaxOpenConns**,***DB.SetMaxIdleConns**, and ***DB.SetConnMaxLifetime** in the database/sql documentation. The read, write, and dial timeouts for each individual connection are configured with the DSN parameters readTimeout, writeTimeout, and timeout, respectively
对上述上述三个方法测试验证有效
测试代码如下(部分):
片段一:
```
var err error
My, err = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?parseTime=true")
if err != nil {
log.Fatal(err.Error())
}
err = My.Ping()
if err != nil {
log.Fatal(err.Error())
}
// Connection pool and timeouts
// 连接池 和 超时
My.SetMaxOpenConns(20) // 最大打开连接数
My.SetMaxIdleConns(10) // 最大空闲连接数
//My.SetConnMaxLifetime(time.Second * 10) // 连接过期时间 如不设置 连接会被一直保持
```
片段二:
```
func (p *Person) GetAll() (persons []Person, err error) {
persons = make([]Person, 0)
rows, err := db.My.Query("SELECT id, firstname, lastname FROM person")
defer rows.Close()
if err != nil {
return
}
time.Sleep(time.Second * 5) //测试连接池效果 保持db连接不释放
for rows.Next() {
var person Person
rows.Scan(&person.Id, &person.FirstName, &person.LastName)
persons = append(persons, person)
}
if err = rows.Err(); err != nil {
return
}
return
}
```
开始测试:
`for ((i=0;i<1000;i++)) do curl http://127.0.0.1:10086/person/all & done`
`netstat -anp | findstr 3306 > 1.txt // windows`
测试结果:
![test.png](https://static.studygolang.com/181227/2a5a5895f76a80e175bf55d24b874c7a.png)
可以看到确实保持住了20个连接,go的db连接池使用和Java中配置连接池一样方便
有疑问加站长微信联系(非本文作者))