-
Notifications
You must be signed in to change notification settings - Fork 13
/
mysql.go
70 lines (62 loc) · 1.35 KB
/
mysql.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package db
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"time"
)
var DB *gorm.DB
type MySQLConfig struct {
Host string
Port int
User string
Password string
Database string
Charset string
MaxOpenConn int
MaxIdleConn int
MaxLifeTimeMin int
}
func Init(mysqlConf *MySQLConfig, redisConf *RedisConfig) error {
if mysqlConf != nil {
err := initMySQL(mysqlConf)
if err != nil {
return err
}
}
if redisConf != nil {
initRedis(redisConf)
}
return nil
}
func initMySQL(mysqlConf *MySQLConfig) error {
url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=true",
mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database, mysqlConf.Charset)
var err error
DB, err = gorm.Open(mysql.Open(url), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: "im_",
SingularTable: true,
//NameReplacer: nil,
//NoLowerCase: false,
},
})
if err != nil {
return err
}
db, err := DB.DB()
if err != nil {
return err
}
if mysqlConf.MaxOpenConn > 0 {
db.SetMaxOpenConns(mysqlConf.MaxOpenConn)
}
if mysqlConf.MaxLifeTimeMin > 0 {
db.SetConnMaxLifetime(time.Duration(mysqlConf.MaxLifeTimeMin) * time.Minute)
}
if mysqlConf.MaxIdleConn > 0 {
db.SetMaxIdleConns(mysqlConf.MaxIdleConn)
}
return nil
}