-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
75 lines (63 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
71
72
73
74
75
package infras
import (
"log"
"time"
"github.com/kumin/go-tpc/pkg/envx"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type MysqlConnector struct {
Client *gorm.DB
}
func MysqlConnectionBuilder(fns ...optionFn) *MysqlConnector {
opt := MysqlDefaultOption
for _, f := range fns {
f(opt)
}
client, err := gorm.Open(mysql.Open(opt.DSN), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
pool, err := client.DB()
if err != nil {
log.Fatal(err)
}
pool.SetMaxOpenConns(opt.MaxConn)
pool.SetConnMaxLifetime(opt.MaxLifetime)
return &MysqlConnector{
Client: client,
}
}
func NewMysqlConnector() *MysqlConnector {
return MysqlConnectionBuilder(
WithDSN(envx.GetString("MYSQL_ADDRS",
"root@tcp(localhost:3306)/kumin_store?charset=utf8&parseTime=True&loc=Local&multiStatements=true")),
WithMaxConn(2),
WithLifetime(1*time.Minute),
)
}
type MysqlOption struct {
DSN string
MaxConn int
MaxLifetime time.Duration
}
var MysqlDefaultOption = &MysqlOption{
MaxConn: 2,
MaxLifetime: 1 * time.Minute,
}
type optionFn func(opt *MysqlOption)
func WithDSN(dsn string) optionFn {
return func(opt *MysqlOption) {
opt.DSN = dsn
}
}
func WithMaxConn(conns int) optionFn {
return func(opt *MysqlOption) {
opt.MaxConn = conns
}
}
func WithLifetime(minus time.Duration) optionFn {
return func(opt *MysqlOption) {
opt.MaxLifetime = minus
}
}