voucher/internal/data/gorm_test.go

105 lines
2.6 KiB
Go

package data
import (
"context"
"errors"
"fmt"
"google.golang.org/protobuf/types/known/durationpb"
"gorm.io/gorm"
"gorm.io/hints"
"sync"
"testing"
"time"
"voucher/internal/biz/vo"
"voucher/internal/conf"
"voucher/internal/data/model"
)
func Test_gorm_db(t *testing.T) {
data := &conf.Data_Database{
Driver: "mysql",
Source: "root:lsxddb123.@tcp(47.108.53.72:3306)/voucher?parseTime=True&loc=Local",
MaxIdle: 20, // 空闲连接池
MaxOpen: 200, // 最大连接数
MaxLifetime: durationpb.New(60), // 5分钟
IsDebug: false,
}
gormDb, cleanup := db(data)
defer cleanup()
start2 := time.Now()
concurrency := 10 // 调整并发数
errCount := 0
var wg sync.WaitGroup
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func(i int) {
defer wg.Done()
ctx := context.Background()
var info model.Order
tx := gormDb.
WithContext(ctx).
Model(model.Order{}).
//Clauses(hints.UseIndex("udx_out_biz_no_type")).
Where(model.Order{Type: vo.OrderTypeCmb.GetValue(), OutBizNo: fmt.Sprintf("174252390990605ngywYrSAGE83e1%d", i)}).
First(&info)
if tx.Error != nil {
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
t.Errorf("未找到记录")
} else {
fmt.Printf("请求错误: %v\n", tx.Error)
errCount += 1
}
}
}(i)
}
wg.Wait()
t.Logf("\n--------------连接请求,总请求耗时: %v,总数: %d, 失败次数: %d--------------\n", time.Since(start2), concurrency, errCount)
}
func Test_db(t *testing.T) {
maxLifetime := durationpb.New(300) // 5分钟
data := &conf.Data_Database{
Driver: "mysql",
Source: "root:lansexiongdi6,@tcp(47.97.27.195:3306)/voucher?parseTime=True&loc=Local",
MaxIdle: 2, // 空闲连接池
MaxOpen: 10, // 最大连接数
MaxLifetime: maxLifetime,
IsDebug: false,
}
gormDb, cleanup := db(data)
defer cleanup()
start2 := time.Now()
errCount := 0
const concurrency = 2
for i := 0; i < concurrency; i++ {
ctx := context.Background()
var info model.Order
tx := gormDb.
WithContext(ctx).
Model(model.Order{}).
Clauses(hints.ForceIndex("udx_out_biz_no_type")).
Where(model.Order{Type: vo.OrderTypeCmb.GetValue(), OutBizNo: fmt.Sprintf("174252390990605ngywYrSAGE83e1%d", i)}).
First(&info)
if tx.Error != nil {
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
t.Errorf("未找到记录")
} else {
fmt.Printf("请求错误: %v\n", tx.Error)
errCount += 1
}
}
}
t.Logf("\n--------------连接请求,总请求耗时: %v,总数: %d, 失败次数: %d--------------\n", time.Since(start2), concurrency, errCount)
}