package db import ( "context" _ "github.com/go-sql-driver/mysql" "golib.gaore.com/GaoreGo/cast" "golib.gaore.com/GaoreGo/grlogs" _ "golib.gaore.com/GaoreGo/grlogs/logs/alils" "io" "os" "time" "xorm.io/core" "xorm.io/xorm" "xorm.io/xorm/log" ) var engines map[string]*xorm.Engine func SelectXorm(name string) *xorm.Engine { if name == "" { name = DEFAULT } return engines[name] } func LoadXorm(dsns map[string]dsnConfig) (err error) { engines = make(map[string]*xorm.Engine) var writer io.Writer = grlogs.GetAli("sql") // 测试环境下输出sql runmode := os.Getenv("CENTER_RUNMODE") for alias, dsn := range dsns { grlogs.GetAli("sql").Debug("init_db 正在加载数据 %s", dsn.Dsn) engine, err := xorm.NewEngine(dsn.Driver, dsn.Dsn) if err != nil { grlogs.GetAli("sql").Critical(err.Error()) } logger := log.NewSimpleLogger(writer) tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, cast.ToString(dsn.Item.Prefix)) engine.SetTableMapper(tbMapper) engine.SetLogger(logger) engine.SetMaxIdleConns(1000) engine.SetMaxOpenConns(1000) engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai") if runmode == "dev" { engine.ShowSQL(true) } ctx, _ := context.WithTimeout(context.Background(), time.Second*5) err = engine.PingContext(ctx) if err != nil { grlogs.GetAli("sql").Critical("---%s--- %s", alias, err.Error()) os.Exit(-1) } else { engines[alias] = engine } } return } type XormInterface interface { Engine() *xorm.Engine }