-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.go
122 lines (91 loc) · 1.99 KB
/
pubsub.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
package gr
import (
"bufio"
"net"
"time"
)
type RedisChannel struct {
Channel string
Data string
}
type PubSub struct {
redis *Redis
conn *net.TCPConn
writer *bufio.Writer
reader *bufio.Reader
done chan bool
listenerDone chan bool
Message chan RedisChannel
}
func rPublish(channel string, message string) [][]byte {
return multiCompile("PUBLISH", channel, message)
}
func newPubSub(redis *Redis) (*PubSub, error) {
ps := new(PubSub)
ps.redis = redis
ps.conn = redis.pool.get()
ps.writer = bufio.NewWriter(ps.conn)
ps.reader = bufio.NewReader(ps.conn)
ps.done = make(chan bool, 1)
ps.listenerDone = make(chan bool, 1)
ps.Message = make(chan RedisChannel, 1000)
return ps, nil
}
func (p *PubSub) subscribe(redisChannels ...string) {
c := multiCompile(append([]string{"SUBSCRIBE"}, redisChannels...)...)
p.channelListener(c)
}
func (p *PubSub) pSubscribe(redisChannels ...string) {
c := multiCompile(append([]string{"PSUBSCRIBE"}, redisChannels...)...)
p.channelListener(c)
}
func (p *PubSub) channelListener(pattern [][]byte) {
write(pattern, p.writer)
p.writer.Flush()
readStringArray(read(p.reader))
//SEND MESSAGE FUNCTION OR TIMEOUT
sendMessage := func(msg []string, i, j int) {
rc := RedisChannel{
Channel: msg[i],
Data: msg[j],
}
select {
case p.Message <- rc:
case <-time.After(time.Second * 2):
}
}
Loop:
for {
//Exit loop if UNSUBSCRIBING
select {
case d := <-p.done:
if d {
close(p.Message)
p.listenerDone <- true
break Loop
}
default:
}
msg, _ := readStringArray(read(p.reader))
switch msg[0] {
case "message":
sendMessage(msg, 1, 2)
case "pmessage":
sendMessage(msg, 2, 3)
}
} //End Loop
}
func (p *PubSub) unSubscribe() {
p.done <- true
c := multiCompile("UNSUBSCRIBE")
write(c, p.writer)
p.writer.Flush()
//WAIT FOR LISTENER TO CLOSE OR TIMEOUT
select {
case <-p.listenerDone:
case <-time.After(time.Second * 2):
}
p.redis.pool.put(p.conn)
p.writer = nil
p.reader = nil
}