-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcpool.go
100 lines (77 loc) · 1.65 KB
/
cpool.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
package rwdb
import (
"database/sql"
"errors"
"sync"
"sync/atomic"
)
// CPool holds the master and slave connection pools
type CPool struct {
pool []*sql.DB
next uint64
lock sync.RWMutex
}
func (c *CPool) nextInPool() int {
if c.poolSize() == 0 {
return -1
}
c.next = atomic.AddUint64(&c.next, 1) % uint64(len(c.pool))
return int(c.next)
}
func (c *CPool) poolSize() int {
c.lock.RLock()
defer c.lock.RUnlock()
return len(c.pool)
}
// AddReader append a db connection to the pool
func (c *CPool) AddReader(db *sql.DB) {
c.lock.Lock()
defer c.lock.Unlock()
if len(c.pool) > 1 {
for i, po := range c.pool[1:] {
if po == nil {
c.pool[i+1] = db
return
}
}
}
c.pool = append(c.pool, db)
}
// AddWriter prepend a db connection to the pool
// Previous writer automatically become a reader
func (c *CPool) AddWriter(db *sql.DB) {
c.lock.Lock()
c.pool = append([]*sql.DB{db}, c.pool...)
c.lock.Unlock()
}
// Reader gets the reader connection next in line
func (c *CPool) Reader() (*sql.DB, error) {
pos := c.nextInPool()
if pos < 0 {
return nil, errors.New("no reader db available")
}
c.lock.RLock()
defer c.lock.RUnlock()
conn := c.pool[pos]
var count int
for conn == nil {
if count = c.nextInPool(); count == pos {
return nil, errors.New("no reader db available")
}
conn = c.pool[count]
}
return conn, nil
}
// Writer gets the writer connection
func (c *CPool) Writer() (*sql.DB, error) {
c.lock.RLock()
defer c.lock.RUnlock()
if len(c.pool) == 0 {
return nil, errors.New("no writer db available")
}
db := c.pool[0]
if db == nil {
return nil, errors.New("no writer db available")
}
return db, nil
}