forked from evalphobia/wizard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
standard_cluster.go
62 lines (51 loc) · 1.37 KB
/
standard_cluster.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
package wizard
import (
"math/rand"
"time"
)
func init() {
// initialized for slave balancing
rand.Seed(time.Now().UnixNano())
}
// StandardCluster is struct for typical(non-sharded) database cluster
type StandardCluster struct {
master *Node
slaves []*Node
}
// NewCluster returns the StandardCluster initialized with master database
func NewCluster(db interface{}) *StandardCluster {
node := NewNode(db)
return &StandardCluster{master: node}
}
// Master returns master database
func (c StandardCluster) Master() *Node {
return c.master
}
// Masters is dummy method for interface
func (c StandardCluster) Masters() []*Node {
return []*Node{c.master}
}
// Slave ramdomly returns the slave database.
// if no slave is registered, master is returned
func (c StandardCluster) Slave() *Node {
if len(c.slaves) == 0 {
return c.master
}
return c.slaves[rand.Intn(len(c.slaves))]
}
// Slaves is dummy method for interface
func (c StandardCluster) Slaves() []*Node {
return []*Node{c.Slave()}
}
// SelectByKey is dummy method for interface
func (c *StandardCluster) SelectByKey(v interface{}) *StandardCluster {
return c
}
// RegisterMaster set new master node
func (c *StandardCluster) RegisterMaster(db interface{}) {
c.master = &Node{db: db}
}
// RegisterSlave adds slave node
func (c *StandardCluster) RegisterSlave(db interface{}) {
c.slaves = append(c.slaves, &Node{db: db})
}