/
db.go
55 lines (46 loc) · 1.51 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package dal
import (
"fmt"
"github.com/PICOF/simple-tiktok/pkg/config"
"github.com/spf13/viper"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
"time"
)
var DB *gorm.DB
var DBConfig *viper.Viper
const ConfigName = "mysql"
func init() {
DB = getDB()
}
func getDB() (myDB *gorm.DB) {
DBConfig = config.GetConfig(ConfigName)
var err error
DSN := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=%s",
DBConfig.GetString("mysql.dsn.username"),
DBConfig.GetString("mysql.dsn.password"),
DBConfig.GetString("mysql.dsn.host"),
DBConfig.GetInt("mysql.dsn.port"),
DBConfig.GetString("mysql.dsn.database"),
DBConfig.GetString("mysql.dsn.charset"),
DBConfig.GetBool("mysql.dsn.parseTime"),
DBConfig.GetString("mysql.dsn.location"),
)
myDB, err = gorm.Open(mysql.New(mysql.Config{
DSN: DSN, // DSN data source name
DefaultStringSize: 256, // string 类型字段的默认长度
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}))
if err != nil {
log.Fatal(err)
}
sqlDB, err := myDB.DB()
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(DBConfig.GetInt("mysql.connPool.maxIdleConn"))
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(DBConfig.GetInt("mysql.connPool.maxOpenConn"))
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(time.Duration(DBConfig.GetInt("mysql.connPool.connMaxLifetime")) * time.Hour)
return
}