golang mysql連線池
阿新 • • 發佈:2020-07-28
配置檔案:
[spu] user_name = xxx password = xxx host = 192.168.1.xxx database = liexin_spu table_prefix =xxx type = mysql #線上地址 #user:passwd@ip:port/databases [supp] user_name = xxx password = xxx host = xxx database = xxx table_prefix =lie_ type = mysql [cms] user_name = xxx password = xxx host = xxx database= xxx table_prefix = type = mysql
配置多個mysql資料庫
package config type BaseDatabase struct { UserName string Password string Host string Database string MaxIdleCons int MaxOpenCons int Prefix string } //多資料庫配置 func BuildDatabaseList() (DatabaseList map[string]BaseDatabase) { return map[string]BaseDatabase{ "spu": { UserName: Get("spu.user_name").String(), Password: Get("spu.password").String(), Host: Get("spu.host").String(), Database: Get("spu.database").String(), Prefix: Get("spu.table_prefix").String(), }, "supp": { UserName: Get("supp.user_name").String(), Password: Get("supp.password").String(), Host: Get("supp.host").String(), Database: Get("supp.database").String(), Prefix: Get("supp.table_prefix").String(), }, "cms": { UserName: Get("cms.user_name").String(), Password: Get("cms.password").String(), Host: Get("cms.host").String(), Database: Get("cms.database").String(), Prefix: Get("cms.table_prefix").String(), }, } }
實現mysql連線池
package mysql import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" "search_server/pkg/config" "search_server/pkg/e" ) var DatabaseConMap map[string]*xorm.Engine func Setup() error { DatabaseConMap = make(map[string]*xorm.Engine, 0) DatabaseList := config.BuildDatabaseList() var err error //迴圈生成資料庫連結 for conName, db := range DatabaseList { userName := db.UserName password := db.Password host := db.Host database := db.Database dataSourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", userName, password, host, database) DatabaseConMap[conName], err = xorm.NewEngine("mysql", dataSourceName) if err != nil { return e.NewFatalError(err.Error()) //這裡返回致命異常 } //日誌列印SQL DatabaseConMap[conName].ShowSQL(true) //設定連線池的空閒數大小 DatabaseConMap[conName].SetMaxIdleConns(db.MaxIdleCons) //設定最大開啟連線數 DatabaseConMap[conName].SetMaxOpenConns(db.MaxOpenCons) } return nil } func Conn(conName string) *xorm.Engine { return DatabaseConMap[conName] }