forked from roistat/go-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 4
/
cluster.go
64 lines (53 loc) · 857 Bytes
/
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
63
64
package clickhouse
import (
"math/rand"
"sync"
)
type PingErrorFunc func(*Conn)
type Cluster struct {
conn []*Conn
active []*Conn
fail PingErrorFunc
mx sync.Mutex
}
func NewCluster(conn ...*Conn) *Cluster {
return &Cluster{
conn: conn,
}
}
func (c *Cluster) IsDown() bool {
c.mx.Lock()
defer c.mx.Unlock()
return len(c.active) < 1
}
func (c *Cluster) OnCheckError(f PingErrorFunc) {
c.fail = f
}
func (c *Cluster) ActiveConn() *Conn {
c.mx.Lock()
defer c.mx.Unlock()
l := len(c.active)
if l < 1 {
return nil
}
return c.active[rand.Intn(l)]
}
func (c *Cluster) Check() {
var (
err error
res []*Conn
)
for _, conn := range c.conn {
err = conn.Ping()
if err == nil {
res = append(res, conn)
} else {
if c.fail != nil {
c.fail(conn)
}
}
}
c.mx.Lock()
defer c.mx.Unlock()
c.active = res
}