1 Star 0 Fork 0

common_go/dbdao

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
db.go 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
liuyanqiang 提交于 2023-03-31 12:53 . dd
package dbdao
import (
"github.com/spf13/cast"
"log"
"sync"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"gitee.com/common_go/config"
)
var initOnce sync.Once
type DBDao struct {
Engine *xorm.EngineGroup
}
var (
dbInstance map[string]*DBDao
curDbPoses map[string]*uint64 // 当前选择的数据库
showSql bool
showExecTime bool
slowDuration time.Duration
maxConn int = 100
maxIdle int = 30
)
func newDBDaoWithParams(hosts []string, driver string) (Db *DBDao) {
Db = new(DBDao)
//engine, err := xorm.NewEngine(driver, host)
engine, err := xorm.NewEngineGroup(driver, hosts)
Db.Engine = engine
//TODO: 增加存活检查
if err != nil {
log.Fatal(err)
}
/*
Db.Engine.Logger.SetLevel(core.LOG_DEBUG)
Db.Engine.ShowSQL = true
Db.Engine.ShowInfo = true
Db.Engine.ShowDebug = true
Db.Engine.ShowErr = true
Db.Engine.ShowWarn = true
*/
Db.Engine.SetMaxOpenConns(maxConn)
Db.Engine.SetMaxIdleConns(maxIdle)
Db.Engine.SetConnMaxLifetime(time.Second * 3000)
Db.Engine.ShowSQL(showSql)
Db.Engine.ShowExecTime(showExecTime)
Db.Engine.SetLogger(dbLogger)
return
}
func Init() {
initOnce.Do(func() {
initDb()
})
}
func initDb() {
dbInstance = make(map[string]*DBDao, 0)
curDbPoses = make(map[string]*uint64)
idc := ""
showLog := config.GetConfStringMap("MysqlConfig")
showSql = showLog["showSql"] == "true"
showExecTime = showLog["showExecTime"] == "true"
slowDuration = time.Duration(cast.ToInt(showLog["slowDuration"])) * time.Millisecond
maxConnConfig := cast.ToInt(showLog["maxConn"])
if maxConnConfig > 0 {
maxConn = maxConnConfig
}
maxIdleConfig := cast.ToInt(showLog["maxIdle"])
if maxIdleConfig > 0 {
maxIdle = maxIdleConfig
}
if maxIdle > maxConn {
maxIdle = maxConn
}
for cluster, hosts := range config.GetConfArrayMap("MysqlCluster") {
//过滤IDC
if cluster == idc {
continue
}
instance := cluster
dbInstance[instance] = newDBDaoWithParams(hosts, "mysql")
curDbPoses[instance] = new(uint64)
}
}
func GetDbInstance(db string) *DBDao {
Init()
if instances, ok := dbInstance[db]; ok {
return instances
} else {
return nil
}
}
//func (this *DBDao) GetSession() *xorm.Session {
// return this.Engine.NewSession()
//}
func (this *DBDao) Close() error {
return this.Engine.Close()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/common_go/dbdao.git
git@gitee.com:common_go/dbdao.git
common_go
dbdao
dbdao
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385