/
pubsub.go
84 lines (75 loc) · 2.02 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
// PubSub implements a simple Redis backed publish-subscribe client.
package pubsub
import "github.com/garyburd/redigo/redis"
// PubSub is a Redis pub/sub client. It uses a connection pool for
// communicating with Redis.
type Conn struct {
pool *redis.Pool
}
// Dial connects to the Redis server with the given network and address.
func Dial(network string, address string, idle int, active int) Conn {
pool := &redis.Pool{
MaxIdle: idle,
MaxActive: active,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial(network, address)
if err != nil {
panic(err.Error())
}
return c, err
},
}
return Conn{pool: pool}
}
// Publish a message with the given topic.
func (c Conn) Publish(topic string, msg []byte) {
con := c.pool.Get()
defer con.Close()
con.Do("PUBLISH", topic, msg)
}
// Subscribe to topic and get messages received for this topic sent to the
// given channel.
func (c Conn) Subscribe(topic string, chn chan<- []byte) {
con := redis.PubSubConn{Conn: c.pool.Get()}
con.Subscribe(topic)
go func(con redis.PubSubConn) {
for {
switch v := con.Receive().(type) {
case redis.Message:
chn <- v.Data
case redis.Subscription:
case error:
break
}
}
con.Unsubscribe(topic)
}(con)
}
// Subscribe to topic and get messages received for this topic sent to the
// given channel as a message with an envelop that contains the topic name.
//
// This can be used for distinguishing messages by topic if multiple
// subscriptions send to a single channel.
func (c Conn) SubscribeMessage(topic string, chn chan<- Message) {
con := redis.PubSubConn{Conn: c.pool.Get()}
con.Subscribe(topic)
go func(con redis.PubSubConn, topic string) {
for {
switch v := con.Receive().(type) {
case redis.Message:
chn <- Message{Topic: topic, Payload: v.Data}
case redis.Subscription:
case error:
break
}
}
con.Unsubscribe(topic)
}(con, topic)
}
// Closes the connection to Redis. This closes the connection pool.
func (c Conn) Close() {
if c.pool == nil {
return
}
c.pool.Close()
}