github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/model/dao/mysql.go (about) 1 package dao 2 3 import ( 4 "fmt" 5 "github.com/OrigamiWang/msd/micro/confparser" 6 logutil "github.com/OrigamiWang/msd/micro/util/log" 7 "gorm.io/driver/mysql" 8 "gorm.io/gorm" 9 ) 10 11 func InitMysql(db *confparser.Database) *gorm.DB { 12 fmt.Println("init mysql...") 13 dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", db.User, db.Password, db.Host, db.Port, db.Name) 14 fmt.Println("dsn: " + dsn) 15 gormDb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ 16 SkipDefaultTransaction: true, 17 }) 18 if err != nil { 19 logutil.Error("Open MySQL connection failed. key: %v", db.Key) 20 return nil 21 } 22 23 sqlDb, _ := gormDb.DB() 24 25 // 通过底层的sqlDb去设置更细粒度的配置 26 maxIdle := db.ExtInt("maxIdle", 0) 27 sqlDb.SetMaxOpenConns(maxIdle) 28 29 maxOpen := db.ExtInt("maxOpen", 8) 30 sqlDb.SetMaxOpenConns(maxOpen) 31 32 lifetime := db.ExtDuration("maxConnLifetime", "0s") 33 sqlDb.SetConnMaxLifetime(lifetime) 34 35 return gormDb 36 }