heritage-api/mysql/mysql.go

106 lines
1.9 KiB
Go
Raw Normal View History

2026-03-12 09:28:19 +00:00
package mysql
import (
"os"
"strconv"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"gorm.io/plugin/dbresolver"
)
/*
docker配置
env MYSQL_DSN=root:root@tcp(mysql:3306)/sample?charset=utf8mb4&parseTime=True&loc=Local
env MYSQL_MAXLIFETIME=2
env MYSQL_MAXIDLECONNS=2
env MYSQL_MAXOPENCONNS=200
env MYSQL_INIT=true
*/
var (
_db *gorm.DB
)
// 创建实例
func newDB() (*gorm.DB, error) {
if _db != nil {
return _db, nil
}
dsn := os.Getenv("MYSQL_DSN")
if dsn == "" {
dsn = "root:root@tcp(127.0.0.1:3306)/mysql?charset=utf8&parseTime=True&loc=Local"
}
maxLifetime := func() int {
c := os.Getenv("MYSQL_MAXLIFETIME")
cc, err := strconv.Atoi(c)
if err != nil {
return 1
}
if cc <= 0 {
return 1
}
if cc >= 1000 {
cc = 1000
}
return cc
}()
maxIdleConns := func() int {
c := os.Getenv("MYSQL_MAXIDLECONNS")
cc, err := strconv.Atoi(c)
if err != nil {
return 1
}
if cc < 0 {
return 0
}
if cc >= 1000 {
cc = 1000
}
return cc
}()
maxOpenConns := func() int {
c := os.Getenv("MYSQL_MAXOPENCONNS")
cc, err := strconv.Atoi(c)
if err != nil {
return 1
}
if cc < 0 {
return 0
}
if cc >= 1000 {
cc = 1000
}
return cc
}()
var err error
_db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: true,
Logger: logger.Default.LogMode(logger.Silent),
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
if err != nil {
return nil, err
}
_db.Use(
dbresolver.Register(dbresolver.Config{
Sources: []gorm.Dialector{mysql.Open(dsn)},
Replicas: []gorm.Dialector{mysql.Open(dsn)},
Policy: dbresolver.RandomPolicy{},
}).SetConnMaxIdleTime(time.Hour).
SetConnMaxLifetime(time.Duration(maxLifetime) * time.Hour).
SetMaxIdleConns(maxIdleConns).
SetMaxOpenConns(maxOpenConns))
return _db, nil
}