-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_manager.go
120 lines (102 loc) · 2.19 KB
/
connection_manager.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
119
120
package hansip
import (
"math/rand"
"sync"
"time"
)
// connectionManager abstracts all database connections we are currently possessing.
// there are one connection to master and n number connections to slaves.
type connectionManager struct {
master *connection
slaves []*connection
activeSlaves []*connection
mutex sync.RWMutex
connCheckDelay time.Duration
closed bool
quitChan chan struct{}
}
func newConnectionManager(connCheckDelay time.Duration) *connectionManager {
manager := &connectionManager{
slaves: []*connection{},
connCheckDelay: connCheckDelay,
quitChan: make(chan struct{}),
}
go manager.loop()
return manager
}
func (m *connectionManager) loop() {
ticker := time.NewTicker(m.connCheckDelay)
for {
select {
case <-ticker.C:
m.updateActiveSlaves()
case <-m.quitChan:
return
}
}
}
func (m *connectionManager) getSlaves() []*connection {
m.mutex.RLock()
slaves := m.slaves
m.mutex.RUnlock()
return slaves
}
func (m *connectionManager) addSlave(conn *connection) {
m.mutex.Lock()
m.slaves = append(m.slaves, conn)
m.mutex.Unlock()
m.updateActiveSlaves()
}
func (m *connectionManager) getActiveSlaves() []*connection {
m.mutex.RLock()
slaves := m.activeSlaves
m.mutex.RUnlock()
return slaves
}
func (m *connectionManager) setActiveSlaves(slaves []*connection) {
m.mutex.Lock()
m.activeSlaves = slaves
m.mutex.Unlock()
}
func (m *connectionManager) updateActiveSlaves() {
current := m.getSlaves()
if len(current) == 0 {
return
}
slaves := make([]*connection, 0, len(current))
for _, conn := range current {
if conn.getConnected() {
slaves = append(slaves, conn)
}
}
m.setActiveSlaves(slaves)
}
func (m *connectionManager) reader() sql {
current := m.getActiveSlaves()
n := len(current)
if n == 0 {
return m.writer()
}
return current[rand.Intn(n)].s
}
func (m *connectionManager) writer() sql {
if !m.master.getConnected() {
return nil
}
return m.master.s
}
func (m *connectionManager) quit() {
if m.closed {
return
}
// stop loop
m.quitChan <- struct{}{}
if m.master != nil {
m.master.quit()
}
for _, conn := range m.slaves {
conn.quit()
}
m.updateActiveSlaves()
m.closed = true
}