-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm_mysql.go
32 lines (29 loc) · 1.01 KB
/
gorm_mysql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package initialize
import (
"time"
"github.com/lihao20110/simple-douyin/server/global"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func GormMysql() *gorm.DB {
m := global.DouYinCONFIG.Mysql
if m.Dbname == "" {
return nil
}
mysqlConfig := mysql.Config{
DSN: m.Dsn(), // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
SkipInitializeWithVersion: false, // 根据版本自动配置
}
db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true})
if err != nil {
global.DouYinLOG.Error("mysql initialize wrong", zap.Error(err))
return nil
}
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns) // SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(m.MaxOpenConns) // SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetConnMaxLifetime(time.Hour) // SetConnMaxLifetime 设置了连接可复用的最大时间
return db
}