forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
267 lines (220 loc) · 5.74 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Package redis provides a Redis broker
package redis
import (
"errors"
"strings"
"time"
"golang.org/x/net/context"
"github.com/garyburd/redigo/redis"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/broker/codec"
"github.com/micro/go-micro/broker/codec/json"
"github.com/micro/go-micro/cmd"
)
func init() {
cmd.DefaultBrokers["redis"] = NewBroker
}
// publication is an internal publication for the Redis broker.
type publication struct {
topic string
message *broker.Message
}
// Topic returns the topic this publication applies to.
func (p *publication) Topic() string {
return p.topic
}
// Message returns the broker message of the publication.
func (p *publication) Message() *broker.Message {
return p.message
}
// Ack sends an acknowledgement to the broker. However this is not supported
// is Redis and therefore this is a no-op.
func (p *publication) Ack() error {
return nil
}
// subscriber proxies and handles Redis messages as broker publications.
type subscriber struct {
codec codec.Codec
conn *redis.PubSubConn
topic string
handle broker.Handler
opts broker.SubscribeOptions
}
// recv loops to receive new messages from Redis and handle them
// as publications.
func (s *subscriber) recv() {
// Close the connection once the subscriber stops receiving.
defer s.conn.Close()
for {
switch x := s.conn.Receive().(type) {
case redis.Message:
var m broker.Message
// Handle error? Only a log would be necessary since this type
// of issue cannot be fixed.
if err := s.codec.Unmarshal(x.Data, &m); err != nil {
break
}
p := publication{
topic: x.Channel,
message: &m,
}
// Handle error? Retry?
if err := s.handle(&p); err != nil {
break
}
// Added for posterity, however Ack is a no-op.
if s.opts.AutoAck {
if err := p.Ack(); err != nil {
break
}
}
case redis.Subscription:
if x.Count == 0 {
return
}
case error:
return
}
}
}
// Options returns the subscriber options.
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
// Topic returns the topic of the subscriber.
func (s *subscriber) Topic() string {
return s.topic
}
// Unsubscribe unsubscribes the subscriber and frees the connection.
func (s *subscriber) Unsubscribe() error {
return s.conn.Unsubscribe()
}
// broker implementation for Redis.
type redisBroker struct {
addr string
pool *redis.Pool
opts broker.Options
bopts *brokerOptions
}
// String returns the name of the broker implementation.
func (b *redisBroker) String() string {
return "redis"
}
// Options returns the options defined for the broker.
func (b *redisBroker) Options() broker.Options {
return b.opts
}
// Address returns the address the broker will use to create new connections.
// This will be set only after Connect is called.
func (b *redisBroker) Address() string {
return b.addr
}
// Init sets or overrides broker options.
func (b *redisBroker) Init(opts ...broker.Option) error {
if b.pool != nil {
return errors.New("redis: cannot init while connected")
}
for _, o := range opts {
o(&b.opts)
}
return nil
}
// Connect establishes a connection to Redis which provides the
// pub/sub implementation.
func (b *redisBroker) Connect() error {
if b.pool != nil {
return nil
}
var addr string
if len(b.opts.Addrs) == 0 || b.opts.Addrs[0] == "" {
addr = "redis://127.0.0.1:6379"
} else {
addr = b.opts.Addrs[0]
if !strings.HasPrefix("redis://", addr) {
addr = "redis://" + addr
}
}
b.addr = addr
b.pool = &redis.Pool{
MaxIdle: b.bopts.maxIdle,
MaxActive: b.bopts.maxActive,
IdleTimeout: b.bopts.idleTimeout,
Dial: func() (redis.Conn, error) {
return redis.DialURL(
b.addr,
redis.DialConnectTimeout(b.bopts.connectTimeout),
redis.DialReadTimeout(b.bopts.readTimeout),
redis.DialWriteTimeout(b.bopts.writeTimeout),
)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return nil
}
// Disconnect closes the connection pool.
func (b *redisBroker) Disconnect() error {
err := b.pool.Close()
b.pool = nil
b.addr = ""
return err
}
// Publish publishes a message.
func (b *redisBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
v, err := b.opts.Codec.Marshal(msg)
if err != nil {
return err
}
conn := b.pool.Get()
_, err = redis.Int(conn.Do("PUBLISH", topic, v))
conn.Close()
return err
}
// Subscribe returns a subscriber for the topic and handler.
func (b *redisBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
var options broker.SubscribeOptions
for _, o := range opts {
o(&options)
}
s := subscriber{
codec: b.opts.Codec,
conn: &redis.PubSubConn{b.pool.Get()},
topic: topic,
handle: handler,
opts: options,
}
// Run the receiver routine.
go s.recv()
if err := s.conn.Subscribe(s.topic); err != nil {
return nil, err
}
return &s, nil
}
// NewBroker returns a new broker implemented using the Redis pub/sub
// protocol. The connection address may be a fully qualified IANA address such
// as: redis://user:secret@localhost:6379/0?foo=bar&qux=baz
func NewBroker(opts ...broker.Option) broker.Broker {
// Default options.
bopts := &brokerOptions{
maxIdle: DefaultMaxIdle,
maxActive: DefaultMaxActive,
idleTimeout: DefaultIdleTimeout,
connectTimeout: DefaultConnectTimeout,
readTimeout: DefaultReadTimeout,
writeTimeout: DefaultWriteTimeout,
}
// Initialize with empty broker options.
options := broker.Options{
Codec: json.NewCodec(),
Context: context.WithValue(context.Background(), optionsKey, bopts),
}
for _, o := range opts {
o(&options)
}
return &redisBroker{
opts: options,
bopts: bopts,
}
}