cutego/refs/database.go

56 lines
1.3 KiB
Go
Raw Normal View History

2023-01-18 17:09:49 +08:00
package refs
import (
"cutego/pkg/config"
2023-01-18 17:46:25 +08:00
"cutego/pkg/logging"
2023-01-18 17:09:49 +08:00
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"time"
)
// 配置数据库
func init() {
2023-01-18 17:46:25 +08:00
logging.InfoLog("database init start...")
2023-01-18 17:09:49 +08:00
var err error
// 配置mysql数据库
ds := config.AppEnvConfig.DataSource
2023-02-02 17:59:03 +08:00
jdbc := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True",
2023-01-18 17:09:49 +08:00
ds.Username,
ds.Password,
ds.Host,
ds.Port,
ds.Database,
ds.Charset)
SqlDB, err = xorm.NewEngine(ds.DbType, jdbc)
if err != nil {
2023-01-18 17:46:25 +08:00
logging.FatalfLog("db error: %#v\n", err.Error())
2023-01-18 17:09:49 +08:00
}
err = SqlDB.Ping()
if err != nil {
2023-01-18 17:46:25 +08:00
logging.FatalfLog("db connect error: %#v\n", err.Error())
2023-01-18 17:09:49 +08:00
}
SqlDB.SetMaxIdleConns(ds.MaxIdleSize)
SqlDB.SetMaxOpenConns(ds.MaxOpenSize)
timer := time.NewTicker(time.Minute * 30)
go func(x *xorm.Engine) {
for _ = range timer.C {
err = x.Ping()
if err != nil {
2023-01-18 17:46:25 +08:00
logging.FatalfLog("db connect error: %#v\n", err.Error())
2023-01-18 17:09:49 +08:00
}
}
}(SqlDB)
SqlDB.ShowSQL(true)
// 开启缓存
SqlDB.SetDefaultCacher(xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000))
2023-02-02 17:59:03 +08:00
// 切换标准时区
location, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
panic("加载时区异常, " + err.Error())
}
SqlDB.SetTZLocation(location)
SqlDB.SetTZDatabase(location)
2023-01-18 17:46:25 +08:00
logging.InfoLog("database init end...")
2023-01-18 17:09:49 +08:00
}