go连接池及超时 测试

倖福魔咒の 提交于 2020-12-18 21:42:58

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
测试结果:

可以看到确实保持住了20个连接,go的db连接池使用和JavaEE框架中配置连接池一样方便

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