120 lines
2.6 KiB
Go
120 lines
2.6 KiB
Go
package mymysql
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"git.makemake.in/test/mycommon/mylog"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
gormLogger "gorm.io/gorm/logger"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
DefaultConfig = &Config{
|
|
Dsn: "root:root@tcp(127.0.0.1:3306)/?loc=Local&charset=utf8mb4&parseTime=true",
|
|
MaxOpenConn: 32,
|
|
MaxIdleConn: 16,
|
|
MaxLifeTime: "1h",
|
|
MaxIdleTime: "10m",
|
|
Debug: true,
|
|
GormLogger: gormLogger.Default.LogMode(gormLogger.Info),
|
|
}
|
|
)
|
|
|
|
type (
|
|
MyDB struct {
|
|
DB *gorm.DB
|
|
SqlDB *sql.DB
|
|
}
|
|
Config struct {
|
|
Dsn string
|
|
MaxOpenConn int
|
|
MaxIdleConn int
|
|
MaxIdleTime string
|
|
MaxLifeTime string
|
|
Debug bool
|
|
GormLogger gormLogger.Interface
|
|
}
|
|
)
|
|
|
|
func New(config *Config) (*MyDB, error) {
|
|
var (
|
|
maxLifeTime, _ = time.ParseDuration(DefaultConfig.MaxLifeTime)
|
|
maxIdleTime, _ = time.ParseDuration(DefaultConfig.MaxIdleTime)
|
|
logger gormLogger.Interface
|
|
)
|
|
|
|
if config.MaxOpenConn <= 0 {
|
|
config.MaxOpenConn = DefaultConfig.MaxOpenConn
|
|
}
|
|
|
|
if config.MaxIdleConn <= 0 {
|
|
config.MaxIdleConn = DefaultConfig.MaxIdleConn
|
|
}
|
|
|
|
if config.MaxLifeTime != "" {
|
|
t, err := time.ParseDuration(config.MaxLifeTime)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse MaxLifeTime err: %s\n", err)
|
|
|
|
}
|
|
maxLifeTime = t
|
|
}
|
|
|
|
if config.MaxIdleTime != "" {
|
|
t, err := time.ParseDuration(config.MaxIdleTime)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse MaxIdleTime err: %s\n", err)
|
|
}
|
|
maxIdleTime = t
|
|
}
|
|
|
|
if config.GormLogger == nil {
|
|
level := gormLogger.Warn
|
|
if config.Debug {
|
|
level = gormLogger.Info
|
|
}
|
|
logger = DefaultGormLogger(level)
|
|
}
|
|
|
|
db, err := gorm.Open(mysql.Open(config.Dsn), &gorm.Config{
|
|
SkipDefaultTransaction: true,
|
|
Logger: logger,
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connect mysql err: %s", err)
|
|
}
|
|
sqlDb, _ := db.DB()
|
|
|
|
sqlDb.SetMaxOpenConns(config.MaxOpenConn)
|
|
sqlDb.SetMaxIdleConns(config.MaxIdleConn)
|
|
sqlDb.SetConnMaxLifetime(maxLifeTime)
|
|
sqlDb.SetConnMaxIdleTime(maxIdleTime)
|
|
return &MyDB{
|
|
DB: db,
|
|
SqlDB: sqlDb,
|
|
}, nil
|
|
}
|
|
|
|
func DefaultGormLogger(level gormLogger.LogLevel) gormLogger.Interface {
|
|
return gormLogger.New(mylog.NewLogger("gorm", mylog.DefaultConfig), gormLogger.Config{
|
|
SlowThreshold: time.Second * 2,
|
|
Colorful: true,
|
|
IgnoreRecordNotFoundError: false,
|
|
ParameterizedQueries: false,
|
|
LogLevel: level,
|
|
})
|
|
}
|
|
|
|
func NewGormLogger(writer gormLogger.Writer, gormLoggerConfig gormLogger.Config) gormLogger.Interface {
|
|
return gormLogger.New(writer, gormLoggerConfig)
|
|
}
|
|
|
|
func (m *MyDB) Close() {
|
|
if m.SqlDB != nil {
|
|
m.SqlDB.Close()
|
|
}
|
|
}
|