forked from lfq7413/tomato
/
redis_pub_sub.go
112 lines (95 loc) · 2.04 KB
/
redis_pub_sub.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
package pubsub
import (
"time"
"github.com/garyburd/redigo/redis"
)
type redisPublisher struct {
address string
password string
p *redis.Pool
}
func (r *redisPublisher) Publish(channel, message string) {
r.do("PUBLISH", channel, message)
}
func (r *redisPublisher) connectInit() {
dialFunc := func() (c redis.Conn, err error) {
c, err = redis.Dial("tcp", r.address)
if err != nil {
return nil, err
}
if r.password != "" {
if _, err := c.Do("AUTH", r.password); err != nil {
c.Close()
return nil, err
}
}
return
}
// initialize a new pool
r.p = &redis.Pool{
MaxIdle: 3,
IdleTimeout: 180 * time.Second,
Dial: dialFunc,
}
}
func (r *redisPublisher) do(commandName string, args ...interface{}) (reply interface{}, err error) {
c := r.p.Get()
defer c.Close()
return c.Do(commandName, args...)
}
type redisSubscriber struct {
psc redis.PubSubConn
listeners []HandlerType
}
func (r *redisSubscriber) Subscribe(channel string) {
r.psc.Subscribe(channel)
}
func (r *redisSubscriber) Unsubscribe(channel string) {
r.psc.Unsubscribe(channel)
}
func (r *redisSubscriber) On(channel string, listener HandlerType) {
r.listeners = append(r.listeners, listener)
}
func (r *redisSubscriber) receive() {
go func() {
for {
switch n := r.psc.Receive().(type) {
case redis.Message:
for _, listener := range r.listeners {
go listener(n.Channel, string(n.Data))
}
}
}
}()
}
func createRedisPublisher(address, password string) *redisPublisher {
m := &redisPublisher{
address: address,
password: password,
}
m.connectInit()
c := m.p.Get()
defer c.Close()
if c.Err() != nil {
panic(c.Err())
}
return m
}
func createRedisSubscriber(address, password string) *redisSubscriber {
c, err := redis.Dial("tcp", address)
if err != nil {
panic(err)
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
panic(err)
}
}
r := &redisSubscriber{
psc: redis.PubSubConn{Conn: c},
listeners: []HandlerType{},
}
r.receive()
return r
}