-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
118 lines (99 loc) · 2.28 KB
/
connection.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// author: wsfuyibing <[email protected]>
// date: 2023-02-18
package db
import (
"context"
"sync"
"time"
"xorm.io/xorm"
)
var (
// Connector
// 连接管理.
Connector *Connection
)
type (
// Connection
// 连接管理接口.
Connection struct {
engines map[string]*xorm.EngineGroup
mu sync.RWMutex
}
)
// GetEngineGroup
// 读取XORM引擎组.
func (o *Connection) GetEngineGroup(keys ...string) (engine *xorm.EngineGroup) {
var (
key = o.key(keys...)
ok bool
)
o.mu.Lock()
defer o.mu.Unlock()
// 复用连接组配置, 若不存在则创建.
if engine, ok = o.engines[key]; !ok {
engine = o.build(key)
o.engines[key] = engine
}
return
}
// GetMaster
// 从Master获取Session.
func (o *Connection) GetMaster(keys ...string) *xorm.Session {
return o.GetEngineGroup(keys...).
Master().
NewSession()
}
// GetMasterWithContext
// 基于Context从Master获取Session.
func (o *Connection) GetMasterWithContext(ctx context.Context, keys ...string) *xorm.Session {
return o.GetMaster(keys...).
Context(ctx)
}
// GetSlave
// 从Slave获取Session.
func (o *Connection) GetSlave(keys ...string) *xorm.Session {
return o.GetEngineGroup(keys...).
Slave().
NewSession()
}
// GetSlaveWithContext
// 基于Context从Slave获取Session.
func (o *Connection) GetSlaveWithContext(ctx context.Context, keys ...string) *xorm.Session {
return o.GetSlave(keys...).
Context(ctx)
}
func (o *Connection) build(key string) *xorm.EngineGroup {
var (
cfg = Config.GetDatabase(key)
eng *xorm.EngineGroup
)
if cfg == nil {
cfg = Config.GetUndefined()
}
eng, _ = xorm.NewEngineGroup(cfg.Driver, cfg.Dsn)
eng.EnableSessionID(*cfg.EnableSession)
eng.SetMapper(cfg.GetMapper())
eng.ShowSQL(*cfg.ShowSQL)
eng.SetMaxIdleConns(cfg.MaxIdle)
eng.SetMaxOpenConns(cfg.MaxOpen)
eng.SetConnMaxLifetime(time.Duration(cfg.MaxLifetime) * time.Second)
eng.SetLogger((&logger{
data: cfg.GetDataName(),
host: cfg.GetHost(),
key: key,
user: cfg.GetUsername(),
internal: cfg.internal,
}).init())
return eng
}
func (o *Connection) init() *Connection {
o.engines = make(map[string]*xorm.EngineGroup)
o.mu = sync.RWMutex{}
return o
}
func (o *Connection) key(keys ...string) string {
if len(keys) > 0 && keys[0] != "" {
return keys[0]
}
return defaultEngine
}