1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package global
- import (
- _ "dm"
- dm "dmgorm2"
- utils "eta_gn/eta_report/utils"
- "fmt"
- "io"
- "log"
- "os"
- "time"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "gorm.io/gorm/schema"
- _ "github.com/go-sql-driver/mysql"
- )
- func InitDm() {
- dmSqlMap := make(map[string]*gorm.DB)
- logWriter := io.MultiWriter(utils.Binlog) //binlog日志,记录到文件中去
- if utils.RunMode == `dev` { // 测试环境,默认输出在控制台,不需要的话,可以注释if里面下面的这行
- logWriter = io.MultiWriter(utils.Binlog, os.Stdout)
- }
- newLogger := logger.New(log.New(logWriter, "\r\n", log.LstdFlags), logger.Config{
- SlowThreshold: 200 * time.Millisecond, //慢sql :200ms
- LogLevel: logger.Info, //记录的日志类型,info代表所有信息都记录
- IgnoreRecordNotFoundError: true, //是否忽略找不到数据错误信息(只是日志记录记录成err还是普通的输出的区别,并不影响业务代码中的:找不到数据行error)
- Colorful: true, //是否颜色输出
- })
- connectDm(utils.MYSQL_URL, "default", newLogger, dmSqlMap, true)
- connectDm(utils.MYSQL_URL_ETA, "eta", newLogger, dmSqlMap, false)
- DmSQL = dmSqlMap
- }
- func connectDm(dsn, aliasName string, newLogger logger.Interface, dmSqlMap map[string]*gorm.DB, isDefault bool) {
- if dsn == `` {
- return
- }
- db, err := gorm.Open(dm.Open(dsn), &gorm.Config{
- Logger: newLogger,
- NamingStrategy: schema.NamingStrategy{
- SingularTable: true, // 表示使用单数表名,启用该选项后,GORM 将不会对表名进行复数化处理
- },
- })
- if err != nil {
- panic(fmt.Errorf("mysql 启动异常,数据库:%s;Err:%s", aliasName, err))
- }
- sqlDB, err := db.DB()
- if err != nil {
- panic(fmt.Errorf("mysql 创建连接池失败,数据库:%s;Err:%s", aliasName, err))
- }
- dmSqlMap[aliasName] = db
- if isDefault {
- DEFAULT_DmSQL = db
- }
- sqlDB.SetMaxIdleConns(50)
- sqlDB.SetMaxOpenConns(100)
- sqlDB.SetConnMaxLifetime(10 * time.Minute)
- }
|