-
Notifications
You must be signed in to change notification settings - Fork 3
/
consumer.go
221 lines (185 loc) · 5.76 KB
/
consumer.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
package bunnify
import (
"errors"
"fmt"
amqp "github.com/rabbitmq/amqp091-go"
)
// Consumer is used for consuming to events from an specified queue.
type Consumer struct {
queueName string
initialized bool
options consumerOption
getNewChannel func() (*amqp.Channel, bool)
}
// NewConsumer creates a consumer for a given queue using the specified connection.
// Information messages such as channel status will be sent to the notification channel
// if it was specified on the connection struct.
// If no QoS is supplied the prefetch count will be of 20.
func (c *Connection) NewConsumer(
queueName string,
opts ...func(*consumerOption)) Consumer {
options := consumerOption{
notificationCh: c.options.notificationChannel,
handlers: make(map[string]wrappedHandler, 0),
prefetchCount: 20,
prefetchSize: 0,
}
for _, opt := range opts {
opt(&options)
}
return Consumer{
queueName: queueName,
options: options,
getNewChannel: func() (*amqp.Channel, bool) {
return c.getNewChannel(NotificationSourceConsumer)
},
}
}
// AddHandlerToConsumer adds a handler for the given routing key.
// It is another way to add handlers when the consumer is already created and cannot use the options.
func AddHandlerToConsumer[T any](consumer *Consumer, routingKey string, handler EventHandler[T]) {
consumer.options.handlers[routingKey] = newWrappedHandler(handler)
}
// Consume will start consuming events from the indicated queue.
// The first time this function is called it will return error if
// handlers or default handler are not specified or if queues, exchanges,
// bindings and qos creation don't succeed. In case this function gets called
// recursively due to channel reconnection, the errors will be pushed to
// the notification channel (if one has been indicated in the connection).
func (c *Consumer) Consume() error {
return c.consume(false)
}
// ConsumeParallel will start consuming events for the indicated queue.
// The first time this function is called it will return error if
// handlers or default handler are not specified and also if queues, exchanges,
// bindings or qos creation don't succeed. In case this function gets called
// recursively due to channel reconnection, the errors will be pushed to
// the notification channel (if one has been indicated in the connection).
// The difference between this and the regular Consume is that this one fires
// a go routine per each message received as opposed of sequentially.
func (c *Consumer) ConsumeParallel() error {
return c.consume(true)
}
func (c *Consumer) consume(parallel bool) error {
channel, connectionClosed := c.getNewChannel()
if connectionClosed {
return fmt.Errorf("connection is already closed by system")
}
// If obtained channel is closed, try again
if channel.IsClosed() {
return c.consume(parallel)
}
if !c.initialized {
if c.options.defaultHandler == nil && len(c.options.handlers) == 0 {
return fmt.Errorf("no handlers specified")
}
if err := c.createExchanges(channel); err != nil {
return fmt.Errorf("failed to declare exchange: %w", err)
}
if err := c.createQueues(channel); err != nil {
return fmt.Errorf("failed to declare queue: %w", err)
}
if err := c.queueBind(channel); err != nil {
return fmt.Errorf("failed to bind queue: %w", err)
}
c.initialized = true
}
if err := channel.Qos(c.options.prefetchCount, c.options.prefetchSize, false); err != nil {
return fmt.Errorf("failed to set qos: %w", err)
}
deliveries, err := channel.Consume(c.queueName, "", false, false, false, false, nil)
if err != nil {
return fmt.Errorf("failed to establish consuming from queue: %w", err)
}
if parallel {
go c.parallelLoop(channel, deliveries)
} else {
go c.loop(channel, deliveries)
}
return nil
}
func (c *Consumer) createExchanges(channel *amqp.Channel) error {
errs := make([]error, 0)
if c.options.exchange != "" {
errs = append(errs, channel.ExchangeDeclare(
c.options.exchange,
"direct",
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // args
))
}
if c.options.deadLetterQueue != "" {
errs = append(errs, channel.ExchangeDeclare(
fmt.Sprintf("%s-exchange", c.options.deadLetterQueue),
"direct",
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // args
))
}
return errors.Join(errs...)
}
func (c *Consumer) createQueues(channel *amqp.Channel) error {
errs := make([]error, 0)
amqpTable := amqp.Table{}
if c.options.quorumQueue {
amqpTable["x-queue-type"] = "quorum"
}
if c.options.retries > 0 {
if !c.options.quorumQueue {
return fmt.Errorf("to enable retries, you need to use quorum queues.")
}
}
if c.options.deadLetterQueue != "" {
amqpTable["x-dead-letter-exchange"] = fmt.Sprintf("%s-exchange", c.options.deadLetterQueue)
amqpTable["x-dead-letter-routing-key"] = ""
_, err := channel.QueueDeclare(
c.options.deadLetterQueue,
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
amqp.Table{},
)
errs = append(errs, err)
}
_, err := channel.QueueDeclare(
c.queueName,
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
amqpTable,
)
errs = append(errs, err)
return errors.Join(errs...)
}
func (c *Consumer) queueBind(channel *amqp.Channel) error {
errs := make([]error, 0)
if c.options.exchange != "" {
for routingKey := range c.options.handlers {
errs = append(errs, channel.QueueBind(
c.queueName,
routingKey,
c.options.exchange,
false,
nil,
))
}
}
if c.options.deadLetterQueue != "" {
errs = append(errs, channel.QueueBind(
c.options.deadLetterQueue,
"",
fmt.Sprintf("%s-exchange", c.options.deadLetterQueue),
false,
nil,
))
}
return errors.Join(errs...)
}