This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package dbhelper
import (
"mygo/conf"
"time"
"github.com/fatih/color"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
const MAX_LIFE_TIME = time.Hour
func init() {
var err error
dbDSN := conf.GetDsn()
color.Red("dbDSN=%v", dbDSN)
DB, err = gorm.Open(mysql.Open(dbDSN), &gorm.Config{})
if err != nil {
panic("连接数据库失败, error=" + err.Error())
}
sqlDB, _ := DB.DB()
sqlDB.SetMaxOpenConns(64) //设置数据库连接池最大连接数
sqlDB.SetMaxIdleConns(20) //连接池最大允许的空闲连接数,如果没有sql任务需要执行的连接数大于20,超过的连接会被连接池关闭。
sqlDB.SetConnMaxLifetime(MAX_LIFE_TIME)
func GetMySqlDB() *gorm.DB {
return DB