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 中配置连接池一样方便


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

查看所有标签

猜你喜欢:

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

人工智能+:AI与IA如何重塑未来

人工智能+:AI与IA如何重塑未来

[美]韩德尔·琼斯(Handel Jones) [中]张臣雄 / 机械工业出版社 / 2018-10 / 55.00

当深度学习模型引发了全世界对人工智能的再次关注时,人工智能迎来第三次高速增长,人工智能(AI)、增强现实(AR)和虚拟现实(VR)正把人类带向新的“智能增强时代”(IA),我们将在不知不觉中接纳机器智能。 针对人类社会长期存在的众多复杂的动态的难题,人机融合智能将会提供全新的解决方案,谷歌、Facebook、微软、亚马逊、腾讯、阿里巴巴、百度等平台巨头纷纷斥千亿巨资布局人工智能的尖端技术;智......一起来看看 《人工智能+:AI与IA如何重塑未来》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具