/
model.go
91 lines (83 loc) · 1.99 KB
/
model.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package mvcs
import (
"errors"
"fmt"
app "github.com/ZYallers/zgin/application"
"github.com/ZYallers/zgin/library/tool"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"sync"
"time"
)
const (
Dialect = "charset=utf8&loc=PRC&parseTime=true&maxAllowedPacket=0&timeout=10s"
retryConnDbMaxTimes = 3
)
type Model struct {
}
type DbCollector struct {
once sync.Once
pointer *gorm.DB
}
func (m *Model) NewClient(dbc *DbCollector, dialect *app.MysqlDialect) *gorm.DB {
var (
err error
fatal bool
)
for i := 1; i <= retryConnDbMaxTimes; i++ {
//log.Printf("getClient %s try --->: %d\n", db, i)
dbc.once.Do(func() {
//log.Printf("openMysql try --->: %s\n", db)
if dbc.pointer, err = m.openMysql(dialect); err == nil {
m.setDefaultConfig(dbc.pointer)
}
})
if err != nil {
if i < retryConnDbMaxTimes {
time.Sleep(time.Second * time.Duration(i))
dbc.once = sync.Once{}
continue
} else {
fatal = true
break
}
}
if err = dbc.pointer.DB().Ping(); err != nil {
if i < retryConnDbMaxTimes {
time.Sleep(time.Second * time.Duration(i))
dbc.once = sync.Once{}
continue
} else {
fatal = true
break
}
}
break
}
if fatal {
defer func() {
errMsg := fmt.Sprintf("new client of mysql occur error: %s", err.Error())
app.Logger.Error(errMsg)
tool.PushSimpleMessage(errMsg, true)
}()
return nil
}
return dbc.pointer
}
func (m *Model) SetMaxOpenConns(db *gorm.DB, num int) {
if num > 0 && num <= 1000 {
db.DB().SetMaxOpenConns(num)
}
}
func (m *Model) openMysql(dialect *app.MysqlDialect) (*gorm.DB, error) {
if dialect == nil {
return nil, errors.New("mysql dialect is nil")
}
tcp := dialect.User + ":" + dialect.Pwd + "@tcp(" + dialect.Host + ":" + dialect.Port + ")/" + dialect.Db + "?" + Dialect
return gorm.Open("mysql", tcp)
}
func (m *Model) setDefaultConfig(db *gorm.DB) {
db.DB().SetMaxOpenConns(8)
db.DB().SetMaxIdleConns(2)
db.DB().SetConnMaxLifetime(time.Second * 30)
}