go连接池及超时 测试

栏目: 数据库 · 发布时间: 7年前

内容简介:在对上述上述三个方法测试验证有效测试代码如下(部分):

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

测试结果:

go连接池及超时 测试

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SQL基础教程

SQL基础教程

MICK / 孙淼、罗勇 / 人民邮电出版社 / 2017-6-1 / CNY 79.00

本书是畅销书《SQL基础教程》第2版,介绍了关系数据库以及用来操作关系数据库的SQL语言的使用方法。书中通过丰富的图示、大量示例程序和详实的操作步骤说明,让读者循序渐进地掌握SQL的基础知识和使用技巧,切实提高编程能力。每章结尾设置有练习题,帮助读者检验对各章内容的理解程度。另外,本书还将重要知识点总结为“法则”,方便读者随时查阅。第2版除了将示例程序更新为对应新版本的DB的SQL之外,还新增了一......一起来看看 《SQL基础教程》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码