github.com/godaddy-x/freego@v1.0.156/ormx/sqld/mysql_manager.go (about) 1 package sqld 2 3 import ( 4 "database/sql" 5 "fmt" 6 _ "github.com/go-sql-driver/mysql" 7 "github.com/godaddy-x/freego/cache" 8 DIC "github.com/godaddy-x/freego/common" 9 "github.com/godaddy-x/freego/utils" 10 "github.com/godaddy-x/freego/zlog" 11 "time" 12 ) 13 14 // mysql配置参数 15 type MysqlConfig struct { 16 DBConfig 17 MaxIdleConns int 18 MaxOpenConns int 19 ConnMaxLifetime int 20 ConnMaxIdleTime int 21 } 22 23 // mysql连接管理器 24 type MysqlManager struct { 25 RDBManager 26 } 27 28 func (self *MysqlManager) Get(option ...Option) (*MysqlManager, error) { 29 if err := self.GetDB(option...); err != nil { 30 return nil, err 31 } 32 return self, nil 33 } 34 35 func (self *MysqlManager) InitConfig(input ...MysqlConfig) error { 36 return self.buildByConfig(nil, input...) 37 } 38 39 func (self *MysqlManager) InitConfigAndCache(manager cache.Cache, input ...MysqlConfig) error { 40 return self.buildByConfig(manager, input...) 41 } 42 43 func (self *MysqlManager) buildByConfig(manager cache.Cache, input ...MysqlConfig) error { 44 for _, v := range input { 45 dsName := DIC.MASTER 46 if len(v.DsName) > 0 { 47 dsName = v.DsName 48 } 49 if _, b := rdbs[dsName]; b { 50 return utils.Error("mysql init failed: [", v.DsName, "] exist") 51 } 52 if len(v.Charset) == 0 { 53 v.Charset = "utf8mb4" 54 } 55 link := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", v.Username, v.Password, v.Host, v.Port, v.Database, v.Charset) 56 db, err := sql.Open("mysql", link) 57 if err != nil { 58 return utils.Error("mysql init failed: ", err) 59 } 60 db.SetMaxIdleConns(v.MaxIdleConns) 61 db.SetMaxOpenConns(v.MaxOpenConns) 62 db.SetConnMaxLifetime(time.Second * time.Duration(v.ConnMaxLifetime)) 63 // db.SetConnMaxIdleTime(time.Second * time.Duration(v.ConnMaxIdleTime)) 64 rdb := &RDBManager{} 65 rdb.Db = db 66 rdb.DsName = dsName 67 rdb.Database = v.Database 68 rdb.CacheManager = manager 69 if v.OpenTx { 70 rdb.OpenTx = v.OpenTx 71 } 72 if v.MongoSync { 73 rdb.MongoSync = v.MongoSync 74 } 75 if v.Timeout > 0 { 76 rdb.Timeout = v.Timeout 77 } 78 rdbs[rdb.DsName] = rdb 79 zlog.Printf("mysql service【%s】has been started successful", dsName) 80 } 81 if len(rdbs) == 0 { 82 return utils.Error("mysql init failed: sessions is nil") 83 } 84 return nil 85 } 86 87 func NewMysql(option ...Option) (*MysqlManager, error) { 88 return new(MysqlManager).Get(option...) 89 }