-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpubsub.go
94 lines (77 loc) · 1.68 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
package goatee
import (
"encoding/json"
"log"
"strconv"
"sync"
"time"
"github.com/gomodule/redigo/redis"
)
type Message struct {
Type string
Channel string
Data []byte
}
type Data struct {
Channel string `json:"channel"`
Payload string `json:"payload"`
CreatedAt string `json:"created_at"`
}
type RedisClient struct {
conn redis.Conn
redis.PubSubConn
sync.Mutex
}
type Client interface {
Receive() (message Message)
}
func NewRedisClient(host string) (*RedisClient, error) {
conn, err := redis.Dial("tcp", host)
if err != nil {
log.Printf("Error dialing redis pubsub: %s", err)
return nil, err
}
pubsub, _ := redis.Dial("tcp", host)
client := RedisClient{conn, redis.PubSubConn{pubsub}, sync.Mutex{}}
if DEBUG {
log.Println("Subscribed to Redis on: ", host)
}
go func() {
for {
time.Sleep(200 * time.Millisecond)
client.Lock()
client.conn.Flush()
client.Unlock()
}
}()
go client.PubsubHub()
h.rclient = &client
h.rconn = conn
return &client, nil
}
func (client *RedisClient) Receive() Message {
switch message := client.PubSubConn.Receive().(type) {
case redis.Message:
return Message{"message", message.Channel, message.Data}
case redis.Subscription:
return Message{message.Kind, message.Channel, []byte(strconv.Itoa(message.Count))}
}
return Message{}
}
func (client *RedisClient) PubsubHub() {
data := Data{}
for {
message := client.Receive()
if message.Type == "message" {
err := json.Unmarshal(message.Data, &data)
if err != nil {
log.Println("Error parsing payload JSON: ", err)
}
data.Channel = message.Channel
h.broadcast <- &data
if DEBUG {
log.Printf("Received: %s", message)
}
}
}
}