package common import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "sync" ) var db *gorm.DB var once sync.Once func GetDb() *gorm.DB { once.Do(func() { db = conn() }) if GetConfig().Service.IsDebug { db = db.Debug() } return db } func conn() *gorm.DB { config := GetConfig() dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", config.Mysql.User, config.Mysql.Password, config.Mysql.Host, config.Mysql.Database) mysqlConn, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(fmt.Sprintf("数据库链接失败:%s", err.Error())) } sqlDb, _ := mysqlConn.DB() sqlDb.SetMaxIdleConns(config.Mysql.Maxidleconns) sqlDb.SetMaxOpenConns(config.Mysql.Maxopenconns) return mysqlConn }