配置文件:
[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] }