beegoinit/db/db_xorm.go
liangzy eba7a63f4b 两项优化
1. 优化json类
2. 优化数据库默认连接配置
2020-08-11 14:31:27 +08:00

86 lines
1.8 KiB
Go

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)
if dsn.Item.MaxIdleConns <= 0 {
engine.SetMaxIdleConns(200)
} else {
engine.SetMaxIdleConns(dsn.Item.MaxIdleConns)
}
if dsn.Item.MaxOpenConns <= 0 {
engine.SetMaxOpenConns(200)
} else {
engine.SetMaxOpenConns(dsn.Item.MaxOpenConns)
}
if dsn.Item.ConnMaxLifetime > 0 {
engine.SetConnMaxLifetime(time.Second * time.Duration(dsn.Item.ConnMaxLifetime))
}
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
}