/
db_mysql.go
84 lines (71 loc) · 2.21 KB
/
db_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
76
77
78
79
80
81
82
83
84
// Package mpdb db_mysql
// User: 姜伟
// Time: 2020-02-19 06:22:40
package mpdb
import (
"sync"
"time"
"github.com/a07061625/gompf/mpf"
"github.com/a07061625/gompf/mpf/mpconstant/errorcode"
"github.com/a07061625/gompf/mpf/mperr"
// 只初始化
_ "github.com/go-sql-driver/mysql"
"xorm.io/xorm"
)
type dbMysql struct {
conn *xorm.Engine
connTime int64
dbName string
refreshTime int64
idleTime int64
}
func (database *dbMysql) connect() {
conf := mpf.NewConfig().GetConfig("db")
database.dbName = conf.GetString("mysql." + mpf.EnvProjectKey() + ".dbname")
dsn := conf.GetString("mysql."+mpf.EnvProjectKey()+".dsn.prefix") + database.dbName + conf.GetString("mysql."+mpf.EnvProjectKey()+".dsn.params")
conn, err := xorm.NewEngine("mysql", dsn)
if err != nil {
panic(mperr.NewDbMysql(errorcode.DbMysqlConnect, "mysql连接失败", err))
}
conn.SetMaxIdleConns(conf.GetInt("mysql." + mpf.EnvProjectKey() + ".conn.idle"))
conn.SetMaxOpenConns(conf.GetInt("mysql." + mpf.EnvProjectKey() + ".conn.open"))
lifeTime := conf.GetInt("mysql." + mpf.EnvProjectKey() + ".conn.life")
conn.SetConnMaxLifetime(time.Duration(lifeTime) * time.Second)
database.conn = conn
database.connTime = time.Now().Unix()
database.idleTime = conf.GetInt64("mysql." + mpf.EnvProjectKey() + ".idle")
database.refreshTime = database.connTime + database.idleTime
}
func (database *dbMysql) Reconnect() {
nowTime := time.Now().Unix()
if database.conn == nil {
database.connect()
} else if database.refreshTime < nowTime {
pingErr := database.conn.Ping()
if pingErr != nil {
database.conn.Close()
database.connect()
}
database.refreshTime = nowTime + database.idleTime
}
}
func (database *dbMysql) GetDbName() string {
return database.dbName
}
func (database *dbMysql) GetConn() *xorm.Engine {
return database.conn
}
var (
onceMysql sync.Once
insMysql *dbMysql
)
func init() {
insMysql = &dbMysql{nil, 0, "", 0, 0}
}
// NewDbMysql NewDbMysql
func NewDbMysql() *dbMysql {
onceMysql.Do(func() {
insMysql.connect()
})
return insMysql
}