-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrabbitmq.go
247 lines (215 loc) · 6.19 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
package rabbitmq
import (
"context"
"encoding/json"
"sync"
"sync/atomic"
"time"
"github.com/golang-queue/queue"
"github.com/golang-queue/queue/core"
"github.com/golang-queue/queue/job"
amqp "github.com/rabbitmq/amqp091-go"
)
var _ core.Worker = (*Worker)(nil)
/*
Worker struct implements the core.Worker interface for RabbitMQ.
It manages the AMQP connection, channel, and task consumption.
Fields:
- conn: AMQP connection to RabbitMQ server.
- channel: AMQP channel for communication.
- stop: Channel to signal worker shutdown.
- stopFlag: Atomic flag to indicate if the worker is stopped.
- stopOnce: Ensures shutdown logic runs only once.
- startOnce: Ensures consumer initialization runs only once.
- opts: Configuration options for the worker.
- tasks: Channel for receiving AMQP deliveries (tasks).
*/
type Worker struct {
conn *amqp.Connection
channel *amqp.Channel
stop chan struct{}
stopFlag int32
stopOnce sync.Once
startOnce sync.Once
opts options
tasks <-chan amqp.Delivery
}
/*
NewWorker creates and initializes a new Worker instance with the provided options.
It establishes a connection to RabbitMQ, sets up the channel, and declares the exchange.
If any step fails, it logs a fatal error and terminates the process.
Parameters:
- opts: Variadic list of Option functions to configure the worker.
Returns:
- Pointer to the initialized Worker.
*/
func NewWorker(opts ...Option) *Worker {
var err error
w := &Worker{
opts: newOptions(opts...),
stop: make(chan struct{}),
tasks: make(chan amqp.Delivery),
}
w.conn, err = amqp.Dial(w.opts.addr)
if err != nil {
w.opts.logger.Fatal("can't connect rabbitmq: ", err)
}
w.channel, err = w.conn.Channel()
if err != nil {
w.opts.logger.Fatal("can't setup channel: ", err)
}
if err := w.channel.ExchangeDeclare(
w.opts.exchangeName, // name
w.opts.exchangeType, // type
true, // durable
false, // auto-deleted
false, // internal
false, // noWait
nil, // arguments
); err != nil {
w.opts.logger.Fatal("can't declares an exchange: ", err)
}
return w
}
/*
startConsumer initializes the consumer for the worker.
It declares the queue, binds it to the exchange, and starts consuming messages.
This method is safe to call multiple times but will only execute once due to sync.Once.
Returns:
- error: Any error encountered during initialization, or nil on success.
*/
func (w *Worker) startConsumer() error {
var initErr error
w.startOnce.Do(func() {
q, err := w.channel.QueueDeclare(
w.opts.queue, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
initErr = err
w.opts.logger.Error("QueueDeclare failed: ", err)
return
}
if err := w.channel.QueueBind(q.Name, w.opts.routingKey, w.opts.exchangeName, false, nil); err != nil {
initErr = err
w.opts.logger.Error("QueueBind failed: ", err)
return
}
w.tasks, err = w.channel.Consume(
q.Name, // queue
w.opts.tag, // consumer
w.opts.autoAck, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
initErr = err
w.opts.logger.Error("Consume failed: ", err)
return
}
})
return initErr
}
/*
Run executes the worker's task processing function.
It delegates the actual task handling to the configured runFunc.
Parameters:
- ctx: Context for cancellation and timeout.
- task: The task message to process.
Returns:
- error: Any error returned by the runFunc.
*/
func (w *Worker) Run(ctx context.Context, task core.TaskMessage) error {
return w.opts.runFunc(ctx, task)
}
/*
Shutdown gracefully stops the worker.
It ensures shutdown logic runs only once, cancels the consumer, and closes the AMQP connection.
If the worker is already stopped, it returns queue.ErrQueueShutdown.
Returns:
- error: Any error encountered during shutdown, or nil on success.
*/
func (w *Worker) Shutdown() (err error) {
if !atomic.CompareAndSwapInt32(&w.stopFlag, 0, 1) {
return queue.ErrQueueShutdown
}
w.stopOnce.Do(func() {
close(w.stop)
if err = w.channel.Cancel(w.opts.tag, true); err != nil {
w.opts.logger.Error("consumer cancel failed: ", err)
}
if err = w.conn.Close(); err != nil {
w.opts.logger.Error("AMQP connection close error: ", err)
}
})
return err
}
/*
Queue publishes a new task message to the RabbitMQ exchange.
If the worker is stopped, it returns queue.ErrQueueShutdown.
Parameters:
- job: The task message to be published.
Returns:
- error: Any error encountered during publishing, or nil on success.
*/
func (w *Worker) Queue(job core.TaskMessage) error {
if atomic.LoadInt32(&w.stopFlag) == 1 {
return queue.ErrQueueShutdown
}
err := w.channel.PublishWithContext(
context.Background(),
w.opts.exchangeName, // exchange
w.opts.routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: amqp.Table{},
ContentType: "text/plain",
ContentEncoding: "",
Body: job.Bytes(),
DeliveryMode: amqp.Transient, // 1=non-persistent, 2=persistent
Priority: 0, // 0-9
})
return err
}
/*
Request retrieves a new task message from the queue.
It starts the consumer if not already started, waits for a message, and unmarshals it into a job.Message.
If no message is received within a timeout, it returns queue.ErrNoTaskInQueue.
Returns:
- core.TaskMessage: The received task message, or nil if none.
- error: Any error encountered, or queue.ErrNoTaskInQueue if no task is available.
*/
func (w *Worker) Request() (core.TaskMessage, error) {
if err := w.startConsumer(); err != nil {
return nil, err
}
clock := 0
loop:
for {
select {
case task, ok := <-w.tasks:
if !ok {
return nil, queue.ErrQueueHasBeenClosed
}
var data job.Message
_ = json.Unmarshal(task.Body, &data)
if !w.opts.autoAck {
_ = task.Ack(w.opts.autoAck)
}
return &data, nil
case <-time.After(1 * time.Second):
if clock == 5 {
break loop
}
clock += 1
}
}
return nil, queue.ErrNoTaskInQueue
}