/
redis.go
113 lines (87 loc) · 2.2 KB
/
redis.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
package services
import (
"context"
"fmt"
"github.com/garyburd/redigo/redis"
)
type redisServer struct {
ctx context.Context
address string
pubChannel string
subChannel string
subConn *redis.PubSubConn
done chan error
input chan []byte
}
func NewRedisServer(host, port, pubChannel, subChannel string) *redisServer {
redisServerAddr := fmt.Sprintf("%s:%s", host, port)
return &redisServer{nil, redisServerAddr, pubChannel, subChannel, nil, nil, make(chan []byte)}
}
func (rs *redisServer) Run(ctx context.Context) error {
fmt.Println("...Connecting to redis on ", rs.address)
conn, err := rs.dial()
if err != nil {
return err
}
rs.ctx = ctx
rs.subscribe(conn)
fmt.Println("Connected to redis!")
return nil
}
func (rs *redisServer) subscribe(cn redis.Conn) {
rs.done = make(chan error, 1)
conn := redis.PubSubConn{Conn: cn}
if err := conn.Subscribe(redis.Args{}.AddFlat(rs.subChannel)...); err != nil {
rs.done <- err
}
rs.subConn = &conn
// Start listening to redis channel messages
go rs.listenEvents()
}
func (rs *redisServer) listenEvents() {
for {
switch n := rs.subConn.Receive().(type) {
case error:
fmt.Println("error message received from redis: ", n.Error())
// rs.done <- n
return
case redis.Message:
fmt.Println("message received from redis: ", n.Data)
rs.input <- n.Data
case redis.Subscription:
fmt.Printf("Subcribed to Redis %s channel!\n", n.Channel)
}
}
}
func (rs *redisServer) Unsubscribe() error {
if err := rs.subConn.Unsubscribe(); err != nil {
return err
}
fmt.Println("Redis sub channel unsubscribed!")
// close connection
defer func() {
rs.subConn.Conn.Close()
fmt.Println("Redis connection closed!")
}()
return nil
}
func (rs *redisServer) Publish(msg string) error {
fmt.Printf("...publishing message to redis %s channel on %s\n", rs.pubChannel, rs.address)
conn, err := rs.dial()
if err != nil {
return err
}
_, err = conn.Do("PUBLISH", rs.pubChannel, msg)
if err != nil {
return err
}
fmt.Println("Message published!")
return nil
}
func (rs *redisServer) dial() (redis.Conn, error) {
conn, err := redis.Dial("tcp", rs.address)
if err != nil {
return nil, err
}
return conn, nil
}