forked from komron-m/rabbitmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
240 lines (203 loc) · 5.7 KB
/
client.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
package rabbitmq
import (
"context"
"errors"
"fmt"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
type ClientConfig struct {
// this callback will be invoked whenever network failure happens or node shuts down
NetworkErrCallback func(*amqp.Error)
// note that this interval is taken into account when on reconnecting multiple times in row
AutoRecoveryInterval time.Duration
// this callback will be invoked whenever connection retry fails or resource freeing returns error
// returning value as bool should indicate whether to keep retrying recovery or not
AutoRecoveryErrCallback func(error) bool
// this callback will be called if restoring a consumer fails after recovery procedure
ConsumerAutoRecoveryErrCallback func(AMQPConsumer, error)
// configurations for setting up dial and new connection
DialConfig
PublisherConfirmEnabled bool
PublisherConfirmNowait bool
ConsumerQos int
ConsumerPrefetchSize int
ConsumerGlobal bool
}
type Client struct {
cfg ClientConfig
connection *amqp.Connection
publisherChan *amqp.Channel
consumerChan *amqp.Channel
consumers []AMQPConsumer
mx sync.RWMutex
wg sync.WaitGroup
}
func NewClient(cfg ClientConfig) (*Client, error) {
client := Client{cfg: cfg}
if err := client.connect(); err != nil {
return nil, err
}
return &client, nil
}
func (c *Client) connect() error {
conn, err := Dial(c.cfg.DialConfig)
if err != nil {
return err
}
// it's recommended to separate publisher and consumer channels in order to avoid heavy control-flows
// https://www.rabbitmq.com/channels.html#flow-control
publisherChannel, err := conn.Channel()
if err != nil {
return err
}
if c.cfg.PublisherConfirmEnabled {
if err := publisherChannel.Confirm(c.cfg.PublisherConfirmNowait); err != nil {
return err
}
}
// create new channel for consumer
consumerChannel, err := conn.Channel()
if err != nil {
return err
}
if err := consumerChannel.Qos(
c.cfg.ConsumerQos,
c.cfg.ConsumerPrefetchSize,
c.cfg.ConsumerGlobal,
); err != nil {
return err
}
// reassign
c.connection = conn
c.publisherChan = publisherChannel
c.consumerChan = consumerChannel
go func() {
errNotifyChan := c.connection.NotifyClose(make(chan *amqp.Error))
for connectionErr := range errNotifyChan {
c.cfg.NetworkErrCallback(connectionErr)
c.reconnect()
}
}()
return nil
}
func (c *Client) reconnect() {
if err := c.Close(); err != nil {
shouldContinue := c.cfg.AutoRecoveryErrCallback(err)
if !shouldContinue {
return
}
}
// try to connect
if err := c.connect(); err != nil {
shouldContinue := c.cfg.AutoRecoveryErrCallback(err)
if shouldContinue {
// when instant reconnect fails, try again after some time
time.AfterFunc(c.cfg.AutoRecoveryInterval, func() {
c.reconnect()
})
}
} else {
// connection was successful, so restore consumers
for _, consumerParam := range c.consumers {
if err := c.consume(consumerParam); err != nil {
c.cfg.ConsumerAutoRecoveryErrCallback(consumerParam, err)
}
}
}
}
func (c *Client) Consume(consumer AMQPConsumer) error {
c.mx.Lock()
defer c.mx.Unlock()
c.consumers = append(c.consumers, consumer)
return c.consume(consumer)
}
func (c *Client) consume(consumer AMQPConsumer) error {
if consumer.DeclareExchange {
if err := c.consumerChan.ExchangeDeclare(
consumer.ExchangeParams.Name,
consumer.ExchangeParams.Type,
consumer.ExchangeParams.Durable,
consumer.ExchangeParams.AutoDelete,
consumer.ExchangeParams.Internal,
consumer.ExchangeParams.Nowait,
consumer.ExchangeParams.Args,
); err != nil {
return err
}
}
queue, err := c.consumerChan.QueueDeclare(
consumer.QueueParams.Name,
consumer.QueueParams.Durable,
consumer.QueueParams.AutoDelete,
consumer.QueueParams.Exclusive,
consumer.QueueParams.Nowait,
consumer.QueueParams.Args,
)
if err != nil {
return err
}
for _, key := range consumer.RoutingKeys {
// The default exchange is a `direct type` with no name (empty string) pre-declared by the broker.
// It has one special property that makes it very useful for simple applications:
// every queue that is created is automatically bound to it with a routing event which is the same as the queue name.
if consumer.ExchangeParams.Name != "" {
if err := c.consumerChan.QueueBind(
queue.Name,
key,
consumer.ExchangeParams.Name,
consumer.QueueBindParams.Nowait,
consumer.QueueBindParams.Args,
); err != nil {
return err
}
}
}
if consumer.IConsumer != nil {
deliveries, err := c.consumerChan.Consume(
consumer.QueueParams.Name,
consumer.ConsumerParams.ConsumerID,
consumer.ConsumerParams.AutoAck,
consumer.ConsumerParams.Exclusive,
consumer.ConsumerParams.NoLocal,
consumer.ConsumerParams.Nowait,
consumer.ConsumerParams.Args,
)
if err != nil {
return err
}
c.wg.Add(1)
go func() {
defer c.wg.Done()
for msg := range deliveries {
consumer.Consume(context.Background(), msg)
}
}()
}
return nil
}
func (c *Client) Publish(ctx context.Context, exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error {
defConfirm, err := c.publisherChan.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, immediate, msg)
if err != nil {
return err
}
success, err := defConfirm.WaitContext(ctx)
if !success {
return errors.Join(err, fmt.Errorf("failed publishing to: exchange: %s, key: %s", exchange, key))
}
return nil
}
func (c *Client) Close() error {
var err error
if !c.connection.IsClosed() {
err = c.publisherChan.Close()
for _, consumer := range c.consumers {
err = c.consumerChan.Cancel(consumer.ConsumerID, false)
}
c.wg.Wait()
err = c.consumerChan.Close()
err = c.connection.Close()
}
return err
}