/
redis_monitor.go
142 lines (108 loc) · 2.43 KB
/
redis_monitor.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package redconf
import (
"fmt"
"strings"
"sync"
"github.com/garyburd/redigo/redis"
)
var (
_ Monitor = (*RedisMonitor)(nil)
)
const (
DefaultSubscribeChannel = "REDCONF:ONCHANGED"
)
type RedisMonitor struct {
address string
password string
channel string
pool *redis.Pool
watchingNamespace map[string]bool
watchLocker sync.Mutex
}
func init() {
RegisterMonitor("redis", NewRedisMonitor)
}
func NewRedisMonitor(opts Options) (monitor Monitor, err error) {
address := ""
password := ""
channel := ""
opts.Get("address", &address)
opts.Get("password", &password)
if exist := opts.Get("channel", &channel); !exist {
channel = DefaultSubscribeChannel
}
if address == "" {
address = "localhost:6379"
}
m := &RedisMonitor{
address: address,
password: password,
channel: channel,
watchingNamespace: make(map[string]bool),
}
m.pool = redis.NewPool(m.getRedisConn, 0)
monitor = m
return
}
func (p *RedisMonitor) Watch(namespace string, callback KeyContentChangedCallback, onError OnWatchingError) (err error) {
p.watchLocker.Lock()
defer p.watchLocker.Unlock()
var exist bool
if _, exist = p.watchingNamespace[namespace]; exist {
err = fmt.Errorf("redconf: namespace of %s already in watching", namespace)
return
}
go p.watchNamespace(namespace, callback, onError)
return
}
func (p *RedisMonitor) watchNamespace(namespace string, callback KeyContentChangedCallback, onError OnWatchingError) {
var err error
defer func() {
p.watchLocker.Lock()
delete(p.watchingNamespace, namespace)
p.watchLocker.Unlock()
if err != nil && onError != nil {
go onError(namespace, err)
}
}()
var conn redis.Conn
if conn, err = p.getRedisConn(); err != nil {
return
}
sub := &redis.PubSubConn{Conn: conn}
if err = sub.Subscribe(p.channel); err != nil {
return
}
for {
switch v := sub.Receive().(type) {
case redis.Message:
if callback != nil {
key := string(v.Data)
if strings.HasPrefix(key, namespace) {
if namespace != "" {
key = strings.TrimPrefix(key, namespace+":")
}
if key != "" {
go callback(namespace, key)
}
}
}
case error:
err = v
return
}
}
}
func (p *RedisMonitor) getRedisConn() (conn redis.Conn, e error) {
conn, e = redis.Dial("tcp", p.address)
if e != nil {
return
}
if p.password != "" {
if _, e = conn.Do("AUTH", p.password); e != nil {
conn.Close()
return
}
}
return
}