「All right reserved, any unauthorized reproduction or transfer is prohibitted」
之前写过了Go 语言 gorm 框架 MySQL 实践,其中对 gorm 框架在操作 MySQL 的各种基础实践,下面分享一下如何使用 gorm 框架对 MySQL 直接进行性能测试的简单实践。
框架支持
这里我使用了一个原始的 Go 语言版本的FunTester
测试框架,现在只有一个基本的方法,实在是因为 Go 语言特性太强了。框架设计的主要思路之一就是利用 Go 语言的闭包和方法参数特性,将一个func()
当做性能测试的主题,通过不断运行这个func()
来实现性能测试。当然还有另外一个思路就是运行一个多线程任务类,类似Java
版本的com.funtester.base.constaint.ThreadBase
抽象类,这样可以设置一些类的属性,绑定一些测试资源,适配更多的测试场景。
// ExecuteRoutineTimes
// @Description: FunTester性能测试执行框架
// @param fun 待执行方法
// @param times 次数
// @param thread 线程数
func ExecuteRoutineTimes(fun func(), t, r int) {
c := make(chan int) //确认所有线程都结束
key := false //用于控制所有线程一起结束
start := futil.Milli()
for i := 0; i < r; i++ {
go func() {
sum := 0
for i := 0; i < t; i++ {
if key {
break
}
fun()
sum++
}
key = true
c <- sum
}()
}
total := 0
for i := 0; i < r; i++ {
num := <-c
total += num
}
end := futil.Milli()
diff := end - start
//total := thread * times
log.Printf("总耗时: %f", float64(diff)/1000)
log.Printf("请求总数: %d", total)
log.Printf("QPS: %f", float64(total)/float64(diff)*1000.0)
}
select
下面演示 select 的性能测试,这里我用了随机 ID 查询的场景。
func TestSelectP(t *testing.T) {
execute.ExecuteRoutineTimes(func() {
var f Funtester
drive.Where("id = ?", futil.RangInt(35, 20000)).First(&f)
},1000,100)
}
delete
这里我使用从 35 开始递增的 ID 进行删除。
func TestDeleteP(t *testing.T) {
var index int32 = 35
execute.ExecuteRoutineTimes(func() {
id := atomic.AddInt32(&index, 1)
drive.Where("id = ?", id).Delete(&Funtester{})
},1000,100)
}
update
这里使用了 select 的用例部分,随机 ID,然后更新 name 字段,随机 10 个长度的字符串。
func TestUpdateP(t *testing.T) {
execute.ExecuteRoutineTimes(func() {
drive.Where("id = ?",futil.RangInt(35, 20000)).Update("name",futil.RandomStr(10))
},1000,100)
}
inset
这里用到了FunTester
字段都是随机生成。
func TestInsertP(t *testing.T) {
execute.ExecuteRoutineTimes(func() {
drive.Create(&Funtester{Name: futil.RandomStr(10),Age: futil.RandomInt(100)})
},1000,100)
}
FunTester 构造方法
type Funtester struct {
gorm.Model
Name string
Age int
}
到这里可以看出,性能测试框架用到的都是 gorm 框架的基础 API 使用,这里 MySQL 连接池的管理工作完全交给了 gorm 框架完成,看资料说非常牛逼,我们只需要设置几个参数。这个使用体现很像HttpClient
设置HTTP
连接池类似,这里我们也可以看出这些优秀的框架使用起来都是非常简单的。
PS:关于 gorm 的基础使用的请参考上一期的文章Go 语言 gorm 框架 MySQL 实践。
Have Fun ~ Tester !
TesterHome 为用户提供「保留所有权利,禁止转载」的选项。
除非获得原作者的单独授权,任何第三方不得转载标注了「All right reserved, any unauthorized reproduction or transfer is prohibitted」的内容,否则均视为侵权。
具体请参见TesterHome 知识产权保护协议。
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
No Reply at the moment.