|
|
package DbUtil
|
|
|
|
|
|
import (
|
|
|
"dsAutoCode/Utils/CommonUtil"
|
|
|
"dsAutoCode/Utils/ConfigUtil"
|
|
|
"fmt"
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
"github.com/xormplus/xorm"
|
|
|
"github.com/xormplus/xorm/log"
|
|
|
"github.com/xormplus/xorm/names"
|
|
|
"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)
|
|
|
}
|
|
|
//设置数据库连接池
|
|
|
Engine.SetMaxOpenConns(100) //设置打开数据库的最大连接数,包含正在使用的连接和连接池的连接。
|
|
|
Engine.SetMaxIdleConns(10) //设置连接池中的保持连接的最大连接数。
|
|
|
Engine.SetConnMaxLifetime(time.Second * 30)
|
|
|
|
|
|
//调用第一次
|
|
|
Engine.Ping()
|
|
|
|
|
|
//这段代码是黄海后加上的 2020-04-16
|
|
|
//通过定时ping保持鲜活
|
|
|
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(names.SnakeMapper{})
|
|
|
|
|
|
//显示+记录SQL日志
|
|
|
f, _ := os.Create(CommonUtil.GetCurrentPath()+"/Logs/sql.log")
|
|
|
Engine.SetLogger(log.NewSimpleLogger(f))
|
|
|
|
|
|
Engine.ShowSQL(true) // 则会在控制台打印出生成的SQL语句
|
|
|
Engine.Logger().SetLevel(log.LOG_DEBUG) //则会在控制台打印info及以上的信息
|
|
|
}
|