72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
package database
|
|
|
|
import (
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type MySQLOptions struct {
|
|
MaxOpenConns int
|
|
MaxIdleConns int
|
|
ConnMaxLifetime time.Duration
|
|
ConnMaxIdleTime time.Duration
|
|
SlowQueryThreshold time.Duration
|
|
}
|
|
|
|
func DefaultMySQLOptions() MySQLOptions {
|
|
return MySQLOptions{
|
|
MaxOpenConns: 50,
|
|
MaxIdleConns: 10,
|
|
ConnMaxLifetime: 30 * time.Minute,
|
|
ConnMaxIdleTime: 5 * time.Minute,
|
|
SlowQueryThreshold: 500 * time.Millisecond,
|
|
}
|
|
}
|
|
|
|
func OpenMySQL(dsn string, logLevel string, appLogger *zap.Logger) (*gorm.DB, error) {
|
|
return OpenMySQLWithOptions(dsn, logLevel, appLogger, DefaultMySQLOptions())
|
|
}
|
|
|
|
func OpenMySQLWithOptions(dsn string, logLevel string, appLogger *zap.Logger, options MySQLOptions) (*gorm.DB, error) {
|
|
defaults := DefaultMySQLOptions()
|
|
if options.MaxOpenConns < 1 {
|
|
options.MaxOpenConns = defaults.MaxOpenConns
|
|
}
|
|
if options.MaxIdleConns < 0 {
|
|
options.MaxIdleConns = defaults.MaxIdleConns
|
|
}
|
|
if options.ConnMaxLifetime <= 0 {
|
|
options.ConnMaxLifetime = defaults.ConnMaxLifetime
|
|
}
|
|
if options.ConnMaxIdleTime < 0 {
|
|
options.ConnMaxIdleTime = defaults.ConnMaxIdleTime
|
|
}
|
|
if options.SlowQueryThreshold <= 0 {
|
|
options.SlowQueryThreshold = defaults.SlowQueryThreshold
|
|
}
|
|
if options.MaxIdleConns > options.MaxOpenConns {
|
|
options.MaxIdleConns = options.MaxOpenConns
|
|
}
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
|
Logger: newGormLoggerWithThreshold(logLevel, appLogger, options.SlowQueryThreshold),
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// 限制连接池,避免单个实例耗尽 MySQL max_connections。
|
|
sqlDB.SetMaxOpenConns(options.MaxOpenConns)
|
|
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
|
|
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
|
|
sqlDB.SetConnMaxIdleTime(options.ConnMaxIdleTime)
|
|
|
|
return db, nil
|
|
}
|