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

87 lines
1.9 KiB
Go

package db
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"golib.gaore.com/GaoreGo/grconfig"
"golib.gaore.com/GaoreGo/grlogs"
"path"
)
const DEFAULT = "default"
var DbPrefix map[string]string = make(map[string]string)
type dsnConfig struct {
Dsn string
Driver string
Item *DbItem
}
type DbItem struct {
User string `yaml:"user"`
Pass string `yaml:"pass"`
Host string `yaml:"host"`
Port int `yaml:"port"`
Name string `yaml:"name"`
Driver string `yaml:"driver"`
Prefix string `yaml:"prefix"`
MaxIdleConns int `yaml:"max_idle_conns"`
MaxOpenConns int `yaml:"max_open_conns"`
ConnMaxLifetime int64 `yaml:"conn_max_lifetime"`
Timeout int `yaml:"timeout"`
}
func (d *DbItem) Dsn() string {
if d.Timeout <= 0 {
d.Timeout = 5
}
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&loc=Local&autocommit=true&timeout=%ds", d.User, d.Pass, d.Host, d.Port, d.Name, d.Timeout)
}
func init() {
Reload()
}
func Reload(dir ...string) {
var err error
var configer *grconfig.Configer
logger := grlogs.GetAli("sql")
defer func() {
if err != nil {
logger.Critical(err.Error())
}
}()
if len(dir) == 0 {
configer = grconfig.New("conf/")
} else {
dir = append(dir, "conf/")
configer = grconfig.New(path.Join(dir...))
}
dsns, err := GetDsn(configer)
if err = LoadXorm(dsns); err != nil {
logger.Critical(err.Error())
}
}
func GetDsn(configer *grconfig.Configer) (DsnList map[string]dsnConfig, err error) {
var items map[string]*DbItem
DsnList = make(map[string]dsnConfig)
err = configer.Item("db", &items)
if err != nil {
return
}
for alias, v := range items {
dsn := v.Dsn()
driver := v.Driver
if driver == "" {
driver = "mysql"
}
DsnList[alias] = dsnConfig{Dsn: dsn, Driver: driver, Item: v}
}
return
}