mycommon/mymysql/mysql.go

152 lines
3.1 KiB
Go
Raw Normal View History

2023-01-15 00:21:08 +08:00
package mymysql
import (
"fmt"
2023-04-21 17:22:17 +08:00
"git.makemake.in/kzkzzzz/mycommon/mylog"
2023-01-15 00:21:08 +08:00
"gorm.io/driver/mysql"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"time"
)
2023-03-20 20:41:36 +08:00
const DefaultKey = "default"
2023-01-15 00:21:08 +08:00
var (
DefaultConfig = &Config{
Dsn: "root:root@tcp(127.0.0.1:3306)/?loc=Local&charset=utf8mb4&parseTime=true",
MaxOpenConn: 32,
2024-06-01 18:17:41 +08:00
MaxIdleConn: 8,
MaxLifeTime: "4h",
MaxIdleTime: "15m",
2023-01-15 00:21:08 +08:00
Debug: true,
GormLogger: gormLogger.Default.LogMode(gormLogger.Info),
}
2023-03-20 20:41:36 +08:00
2023-03-20 20:53:18 +08:00
instanceMap = make(map[string]*gorm.DB)
2023-01-15 00:21:08 +08:00
)
type (
Config struct {
Dsn string
MaxOpenConn int
MaxIdleConn int
MaxIdleTime string
MaxLifeTime string
Debug bool
GormLogger gormLogger.Interface
}
)
2024-06-01 18:17:41 +08:00
func DB(key ...string) *gorm.DB {
2023-03-20 20:41:36 +08:00
var key0 string
if len(key) > 0 {
key0 = key[0]
} else {
key0 = DefaultKey
}
instance, ok := instanceMap[key0]
if !ok {
2023-05-17 19:46:45 +08:00
panic(fmt.Errorf("mysql %s not config", key0))
2023-03-20 20:41:36 +08:00
}
return instance
}
2023-04-21 18:18:58 +08:00
func InitDefault(config *Config) error {
return Init(DefaultKey, config)
2023-03-20 20:41:36 +08:00
}
2023-04-21 18:18:58 +08:00
func Init(key string, config *Config) error {
2023-05-18 17:52:26 +08:00
db, err := New(config)
if err != nil {
return err
}
instanceMap[key] = db
return nil
}
func New(config *Config) (*gorm.DB, error) {
2023-01-15 00:21:08 +08:00
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 {
2023-05-18 17:52:26 +08:00
return nil, fmt.Errorf("parse MaxLifeTime err: %s\n", err)
2023-01-15 00:21:08 +08:00
}
maxLifeTime = t
}
if config.MaxIdleTime != "" {
t, err := time.ParseDuration(config.MaxIdleTime)
if err != nil {
2023-05-18 17:52:26 +08:00
return nil, fmt.Errorf("parse MaxIdleTime err: %s\n", err)
2023-01-15 00:21:08 +08:00
}
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 {
2023-05-18 17:52:26 +08:00
return nil, fmt.Errorf("connect mysql err: %s", err)
2023-01-15 00:21:08 +08:00
}
sqlDb, _ := db.DB()
sqlDb.SetMaxOpenConns(config.MaxOpenConn)
sqlDb.SetMaxIdleConns(config.MaxIdleConn)
sqlDb.SetConnMaxLifetime(maxLifeTime)
sqlDb.SetConnMaxIdleTime(maxIdleTime)
2023-03-20 20:41:36 +08:00
2023-05-18 17:52:26 +08:00
return db, nil
2023-01-15 00:21:08 +08:00
}
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)
}
2024-06-01 18:28:09 +08:00
func CloseDB(key string) {
2024-06-01 18:17:41 +08:00
db, _ := DB(key).DB()
2023-03-20 20:53:18 +08:00
db.Close()
2023-03-20 20:41:36 +08:00
}
2024-06-01 18:28:09 +08:00
func CloseAllDB() {
2023-03-20 20:53:18 +08:00
for _, v := range instanceMap {
db, _ := v.DB()
db.Close()
}
2023-03-20 20:41:36 +08:00
}