You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package DbUtil
import (
"dsBaseRpc/Utils/ConfigUtil"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/xormplus/core"
"github.com/xormplus/xorm"
"github.com/xormplus/xorm/log"
"os"
"time"
)
var Engine *xorm.Engine
func init() {
host := ConfigUtil.MysqlIp
port := ConfigUtil.MysqlPort
user := ConfigUtil.MysqlUser
dbname := ConfigUtil.MysqlDataBase
password := ConfigUtil.MysqlPwd
//mysql
master := fmt.Sprintf("%s:%s@%s(%s:%s)/%s?charset=utf8", user, password, "tcp", host, port, dbname)
var err error
Engine, err = xorm.NewEngine("mysql", master)
if err != nil {
fmt.Println(err)
}
//注册SqlMap配置可选功能如应用中无需使用SqlMap可无需初始化
err = Engine.RegisterSqlMap(xorm.Xml("./Sql", ".xml"))
if err != nil {
fmt.Println(err)
}
//设置数据库连接池
Engine.SetMaxOpenConns(100) //设置打开数据库的最大连接数,包含正在使用的连接和连接池的连接。
Engine.SetMaxIdleConns(10) //设置连接池中的保持连接的最大连接数。
Engine.SetConnMaxLifetime(time.Second * 30)
//打开xorm的sql日志
Engine.ShowSQL(true)
//调用第一次
Engine.Ping()
//这段代码是黄海后加上的 2020-04-16
//通过定时ping保持鲜活
// 创建完成engine之后并没有立即连接数据库此时可以通过engine.Ping()来进行数据库的连接测试是否可以连接到数据库。
// 另外对于某些数据库有连接超时设置的可以通过起一个定期Ping的Go程来保持连接鲜活。
go func() {
for {
//https://studygolang.com/articles/12617
time.Sleep(time.Duration(10) * time.Second)
Engine.Ping()
}
}()
//设置数据时区
var location *time.Location
location, err = time.LoadLocation("Asia/Shanghai")
Engine.TZLocation = location
//与 struct的映射方式这里采用蛇型方法默认是蛇形
Engine.SetTableMapper(core.SnakeMapper{})
//显示+记录SQL日志
f, _ := os.Create(ConfigUtil.DistributeRemotePath + "sql.log")
Engine.SetLogger(log.NewSimpleLogger(f))
Engine.ShowSQL(true) // 则会在控制台打印出生成的SQL语句
Engine.Logger().SetLevel(log.LOG_DEBUG) //则会在控制台打印info及以上的信息
}