/
rabbitmq.go
394 lines (321 loc) · 8.09 KB
/
rabbitmq.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Package rabbitmq provides a RabbitMQ broker
package rabbitmq
import (
"context"
"errors"
"sync"
"time"
"github.com/streadway/amqp"
"go-micro.dev/v4/broker"
"go-micro.dev/v4/cmd"
)
type rbroker struct {
conn *rabbitMQConn
addrs []string
opts broker.Options
prefetchCount int
prefetchGlobal bool
mtx sync.Mutex
wg sync.WaitGroup
}
type subscriber struct {
mtx sync.Mutex
mayRun bool
opts broker.SubscribeOptions
topic string
ch *rabbitMQChannel
durableQueue bool
queueArgs map[string]interface{}
r *rbroker
fn func(msg amqp.Delivery)
headers map[string]interface{}
}
type publication struct {
d amqp.Delivery
m *broker.Message
t string
err error
}
func init() {
cmd.DefaultBrokers["rabbitmq"] = NewBroker
}
func (p *publication) Ack() error {
return p.d.Ack(false)
}
func (p *publication) Error() error {
return p.err
}
func (p *publication) Topic() string {
return p.t
}
func (p *publication) Message() *broker.Message {
return p.m
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.opts
}
func (s *subscriber) Topic() string {
return s.topic
}
func (s *subscriber) Unsubscribe() error {
s.mtx.Lock()
defer s.mtx.Unlock()
s.mayRun = false
if s.ch != nil {
return s.ch.Close()
}
return nil
}
func (s *subscriber) resubscribe() {
minResubscribeDelay := 100 * time.Millisecond
maxResubscribeDelay := 30 * time.Second
expFactor := time.Duration(2)
reSubscribeDelay := minResubscribeDelay
//loop until unsubscribe
for {
s.mtx.Lock()
mayRun := s.mayRun
s.mtx.Unlock()
if !mayRun {
// we are unsubscribed, showdown routine
return
}
select {
//check shutdown case
case <-s.r.conn.close:
//yep, its shutdown case
return
//wait until we reconect to rabbit
case <-s.r.conn.waitConnection:
// When the connection is disconnected, the waitConnection will be re-assigned, so '<-s.r.conn.waitConnection' maybe blocked.
// Here, it returns once a second, and then the latest waitconnection will be used
case <-time.After(time.Second):
continue
}
// it may crash (panic) in case of Consume without connection, so recheck it
s.r.mtx.Lock()
if !s.r.conn.connected {
s.r.mtx.Unlock()
continue
}
ch, sub, err := s.r.conn.Consume(
s.opts.Queue,
s.topic,
s.headers,
s.queueArgs,
s.opts.AutoAck,
s.durableQueue,
)
s.r.mtx.Unlock()
switch err {
case nil:
reSubscribeDelay = minResubscribeDelay
s.mtx.Lock()
s.ch = ch
s.mtx.Unlock()
default:
if reSubscribeDelay > maxResubscribeDelay {
reSubscribeDelay = maxResubscribeDelay
}
time.Sleep(reSubscribeDelay)
reSubscribeDelay *= expFactor
continue
}
for d := range sub {
s.r.wg.Add(1)
s.fn(d)
s.r.wg.Done()
}
}
}
func (r *rbroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error {
m := amqp.Publishing{
Body: msg.Body,
Headers: amqp.Table{},
}
options := broker.PublishOptions{}
for _, o := range opts {
o(&options)
}
if options.Context != nil {
if value, ok := options.Context.Value(deliveryMode{}).(uint8); ok {
m.DeliveryMode = value
}
if value, ok := options.Context.Value(priorityKey{}).(uint8); ok {
m.Priority = value
}
if value, ok := options.Context.Value(contentType{}).(string); ok {
m.ContentType = value
}
if value, ok := options.Context.Value(contentEncoding{}).(string); ok {
m.ContentEncoding = value
}
if value, ok := options.Context.Value(correlationID{}).(string); ok {
m.CorrelationId = value
}
if value, ok := options.Context.Value(replyTo{}).(string); ok {
m.ReplyTo = value
}
if value, ok := options.Context.Value(expiration{}).(string); ok {
m.Expiration = value
}
if value, ok := options.Context.Value(messageID{}).(string); ok {
m.MessageId = value
}
if value, ok := options.Context.Value(timestamp{}).(time.Time); ok {
m.Timestamp = value
}
if value, ok := options.Context.Value(typeMsg{}).(string); ok {
m.Type = value
}
if value, ok := options.Context.Value(userID{}).(string); ok {
m.UserId = value
}
if value, ok := options.Context.Value(appID{}).(string); ok {
m.AppId = value
}
}
for k, v := range msg.Header {
m.Headers[k] = v
}
if r.conn == nil {
return errors.New("connection is nil")
}
return r.conn.Publish(r.conn.exchange.Name, topic, m)
}
func (r *rbroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
var ackSuccess bool
if r.conn == nil {
return nil, errors.New("not connected")
}
opt := broker.SubscribeOptions{
AutoAck: true,
}
for _, o := range opts {
o(&opt)
}
// Make sure context is setup
if opt.Context == nil {
opt.Context = context.Background()
}
ctx := opt.Context
if subscribeContext, ok := ctx.Value(subscribeContextKey{}).(context.Context); ok && subscribeContext != nil {
ctx = subscribeContext
}
var requeueOnError bool
requeueOnError, _ = ctx.Value(requeueOnErrorKey{}).(bool)
var durableQueue bool
durableQueue, _ = ctx.Value(durableQueueKey{}).(bool)
var qArgs map[string]interface{}
if qa, ok := ctx.Value(queueArgumentsKey{}).(map[string]interface{}); ok {
qArgs = qa
}
var headers map[string]interface{}
if h, ok := ctx.Value(headersKey{}).(map[string]interface{}); ok {
headers = h
}
if bval, ok := ctx.Value(ackSuccessKey{}).(bool); ok && bval {
opt.AutoAck = false
ackSuccess = true
}
fn := func(msg amqp.Delivery) {
header := make(map[string]string)
for k, v := range msg.Headers {
header[k], _ = v.(string)
}
// Messages sent from other frameworks to rabbitmq do not have this header.
// The 'RoutingKey' in the message can be used as this header.
// Then the message can be transfered to the subscriber which bind this topic.
msgTopic := header["Micro-Topic"]
if msgTopic == "" {
header["Micro-Topic"] = msg.RoutingKey
}
m := &broker.Message{
Header: header,
Body: msg.Body,
}
p := &publication{d: msg, m: m, t: msg.RoutingKey}
p.err = handler(p)
if p.err == nil && ackSuccess && !opt.AutoAck {
msg.Ack(false)
} else if p.err != nil && !opt.AutoAck {
msg.Nack(false, requeueOnError)
}
}
sret := &subscriber{topic: topic, opts: opt, mayRun: true, r: r,
durableQueue: durableQueue, fn: fn, headers: headers, queueArgs: qArgs}
go sret.resubscribe()
return sret, nil
}
func (r *rbroker) Options() broker.Options {
return r.opts
}
func (r *rbroker) String() string {
return "rabbitmq"
}
func (r *rbroker) Address() string {
if len(r.addrs) > 0 {
return r.addrs[0]
}
return ""
}
func (r *rbroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&r.opts)
}
r.addrs = r.opts.Addrs
return nil
}
func (r *rbroker) Connect() error {
if r.conn == nil {
r.conn = newRabbitMQConn(r.getExchange(), r.opts.Addrs, r.getPrefetchCount(), r.getPrefetchGlobal())
}
conf := defaultAmqpConfig
if auth, ok := r.opts.Context.Value(externalAuth{}).(ExternalAuthentication); ok {
conf.SASL = []amqp.Authentication{&auth}
}
conf.TLSClientConfig = r.opts.TLSConfig
return r.conn.Connect(r.opts.Secure, &conf)
}
func (r *rbroker) Disconnect() error {
if r.conn == nil {
return errors.New("connection is nil")
}
ret := r.conn.Close()
r.wg.Wait() // wait all goroutines
return ret
}
func NewBroker(opts ...broker.Option) broker.Broker {
options := broker.Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return &rbroker{
addrs: options.Addrs,
opts: options,
}
}
func (r *rbroker) getExchange() Exchange {
ex := DefaultExchange
if e, ok := r.opts.Context.Value(exchangeKey{}).(string); ok {
ex.Name = e
}
if d, ok := r.opts.Context.Value(durableExchange{}).(bool); ok {
ex.Durable = d
}
return ex
}
func (r *rbroker) getPrefetchCount() int {
if e, ok := r.opts.Context.Value(prefetchCountKey{}).(int); ok {
return e
}
return DefaultPrefetchCount
}
func (r *rbroker) getPrefetchGlobal() bool {
if e, ok := r.opts.Context.Value(prefetchGlobalKey{}).(bool); ok {
return e
}
return DefaultPrefetchGlobal
}