如下代码:
package main
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"log"
"os"
"sync"
"time"
)
var db *gorm.DB
var err error
func init() {
var gormConfig gorm.Config
gormConfig.NamingStrategy = schema.NamingStrategy{
SingularTable: true, // use singular table name, table for `User` would be `user` with this option enabled
}
sqlLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
gormConfig.Logger = sqlLogger
//mysql
var dbDsn = "user:password@tcp(host:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
// https://gorm.io/docs/gorm_config.html
db, err = gorm.Open(mysql.Open(dbDsn), &gormConfig)
if err != nil {
log.Fatalf("model base init err: %v", err)
}
//setConn()
}
func setConn() {
mysqlDb, err := db.DB()
if err != nil {
panic(err)
}
mysqlDb.SetMaxIdleConns(20)
mysqlDb.SetMaxOpenConns(200)
}
func close() {
mysqlDb, err := db.DB()
if err != nil {
panic(err)
}
mysqlDb.Close()
}
func modelSelect(wg sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 20; i++ {
var result = make(map[string]interface{}, 0)
db.Table("test").Where("id=1").Find(&result)
}
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go modelSelect(wg)
}
wg.Wait()
}
当循环此处增加到一定程度的时候,会报 connect: cannot assign requested address 这种错误,可以控制连接池的参数来避免改错误。
如上代码只要打开 setConn的注释即可