forked from spring-projects/spring-amqp
/
BlockingQueueConsumer.java
408 lines (347 loc) · 12.9 KB
/
BlockingQueueConsumer.java
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.amqp.rabbit.listener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils;
import org.springframework.amqp.rabbit.connection.RabbitUtils;
import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;
import com.rabbitmq.utility.Utility;
/**
* Specialized consumer encapsulating knowledge of the broker connections and having its own lifecycle (start and stop).
*
* @author Mark Pollack
* @author Dave Syer
* @author Gary Russell
*
*/
public class BlockingQueueConsumer {
private static Log logger = LogFactory.getLog(BlockingQueueConsumer.class);
// This must be an unbounded queue or we risk blocking the Connection thread.
private final BlockingQueue<Delivery> queue = new LinkedBlockingQueue<Delivery>();
// When this is non-null the connection has been closed (should never happen in normal operation).
private volatile ShutdownSignalException shutdown;
private final String[] queues;
private final int prefetchCount;
private final boolean transactional;
private Channel channel;
private InternalConsumer consumer;
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private final AcknowledgeMode acknowledgeMode;
private final ConnectionFactory connectionFactory;
private final MessagePropertiesConverter messagePropertiesConverter;
private final ActiveObjectCounter<BlockingQueueConsumer> activeObjectCounter;
private Set<Long> deliveryTags = new LinkedHashSet<Long>();
private final boolean defaultRequeuRejected;
/**
* Create a consumer. The consumer must not attempt to use the connection factory or communicate with the broker
* until it is started. RequeueRejected defaults to true.
*/
public BlockingQueueConsumer(ConnectionFactory connectionFactory,
MessagePropertiesConverter messagePropertiesConverter,
ActiveObjectCounter<BlockingQueueConsumer> activeObjectCounter, AcknowledgeMode acknowledgeMode,
boolean transactional, int prefetchCount, String... queues) {
this(connectionFactory, messagePropertiesConverter, activeObjectCounter,
acknowledgeMode, transactional, prefetchCount, true, queues);
}
/**
* Create a consumer. The consumer must not attempt to use the connection factory or communicate with the broker
* until it is started.
*/
public BlockingQueueConsumer(ConnectionFactory connectionFactory,
MessagePropertiesConverter messagePropertiesConverter,
ActiveObjectCounter<BlockingQueueConsumer> activeObjectCounter, AcknowledgeMode acknowledgeMode,
boolean transactional, int prefetchCount, boolean defaultRequeueRejected, String... queues) {
this.connectionFactory = connectionFactory;
this.messagePropertiesConverter = messagePropertiesConverter;
this.activeObjectCounter = activeObjectCounter;
this.acknowledgeMode = acknowledgeMode;
this.transactional = transactional;
this.prefetchCount = prefetchCount;
this.defaultRequeuRejected = defaultRequeueRejected;
this.queues = queues;
}
public Channel getChannel() {
return channel;
}
public String getConsumerTag() {
return consumer.getConsumerTag();
}
/**
* Check if we are in shutdown mode and if so throw an exception.
*/
private void checkShutdown() {
if (shutdown != null) {
throw Utility.fixStackTrace(shutdown);
}
}
/**
* If this is a non-POISON non-null delivery simply return it. If this is POISON we are in shutdown mode, throw
* shutdown. If delivery is null, we may be in shutdown mode. Check and see.
*
* @throws InterruptedException
*/
private Message handle(Delivery delivery) throws InterruptedException {
if ((delivery == null && shutdown != null)) {
throw shutdown;
}
if (delivery == null) {
return null;
}
byte[] body = delivery.getBody();
Envelope envelope = delivery.getEnvelope();
MessageProperties messageProperties = this.messagePropertiesConverter.toMessageProperties(
delivery.getProperties(), envelope, "UTF-8");
messageProperties.setMessageCount(0);
Message message = new Message(body, messageProperties);
if (logger.isDebugEnabled()) {
logger.debug("Received message: " + message);
}
deliveryTags.add(messageProperties.getDeliveryTag());
return message;
}
/**
* Main application-side API: wait for the next message delivery and return it.
*
* @return the next message
* @throws InterruptedException if an interrupt is received while waiting
* @throws ShutdownSignalException if the connection is shut down while waiting
*/
public Message nextMessage() throws InterruptedException, ShutdownSignalException {
logger.trace("Retrieving delivery for " + this);
return handle(queue.take());
}
/**
* Main application-side API: wait for the next message delivery and return it.
*
* @param timeout timeout in millisecond
* @return the next message or null if timed out
* @throws InterruptedException if an interrupt is received while waiting
* @throws ShutdownSignalException if the connection is shut down while waiting
*/
public Message nextMessage(long timeout) throws InterruptedException, ShutdownSignalException {
if (logger.isDebugEnabled()) {
logger.debug("Retrieving delivery for " + this);
}
checkShutdown();
return handle(queue.poll(timeout, TimeUnit.MILLISECONDS));
}
public void start() throws AmqpException {
if (logger.isDebugEnabled()) {
logger.debug("Starting consumer " + this);
}
this.channel = ConnectionFactoryUtils.getTransactionalResourceHolder(connectionFactory, transactional)
.getChannel();
this.consumer = new InternalConsumer(channel);
this.deliveryTags.clear();
this.activeObjectCounter.add(this);
try {
if (!acknowledgeMode.isAutoAck()) {
// Set basicQos before calling basicConsume (otherwise if we are not acking the broker
// will send blocks of 100 messages)
channel.basicQos(prefetchCount);
}
for (int i = 0; i < queues.length; i++) {
channel.queueDeclarePassive(queues[i]);
}
} catch (IOException e) {
this.activeObjectCounter.release(this);
throw new FatalListenerStartupException("Cannot prepare queue for listener. "
+ "Either the queue doesn't exist or the broker will not allow us to use it.", e);
}
try {
for (int i = 0; i < queues.length; i++) {
channel.basicConsume(queues[i], acknowledgeMode.isAutoAck(), consumer);
if (logger.isDebugEnabled()) {
logger.debug("Started on queue '" + queues[i] + "': " + this);
}
}
} catch (IOException e) {
throw RabbitUtils.convertRabbitAccessException(e);
}
}
public void stop() {
cancelled.set(true);
if (consumer != null && consumer.getChannel() != null && consumer.getConsumerTag() != null) {
RabbitUtils.closeMessageConsumer(consumer.getChannel(), consumer.getConsumerTag(), transactional);
}
logger.debug("Closing Rabbit Channel: " + channel);
// This one never throws exceptions...
RabbitUtils.closeChannel(channel);
deliveryTags.clear();
}
private class InternalConsumer extends DefaultConsumer {
public InternalConsumer(Channel channel) {
super(channel);
}
@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
if (logger.isDebugEnabled()) {
logger.debug("Received shutdown signal for consumer tag=" + consumerTag, sig);
}
shutdown = sig;
// The delivery tags will be invalid if the channel shuts down
deliveryTags.clear();
}
@Override
public void handleCancelOk(String consumerTag) {
if (logger.isDebugEnabled()) {
logger.debug("Received cancellation notice for " + BlockingQueueConsumer.this);
}
// Signal to the container that we have been cancelled
activeObjectCounter.release(BlockingQueueConsumer.this);
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
if (cancelled.get()) {
if (acknowledgeMode.isTransactionAllowed()) {
return;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Storing delivery for " + BlockingQueueConsumer.this);
}
try {
// N.B. we can't use a bounded queue and offer() here with a timeout
// in case the connection thread gets blocked
queue.put(new Delivery(envelope, properties, body));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* Encapsulates an arbitrary message - simple "bean" holder structure.
*/
private static class Delivery {
private final Envelope envelope;
private final AMQP.BasicProperties properties;
private final byte[] body;
public Delivery(Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
this.envelope = envelope;
this.properties = properties;
this.body = body;
}
public Envelope getEnvelope() {
return envelope;
}
public BasicProperties getProperties() {
return properties;
}
public byte[] getBody() {
return body;
}
}
@Override
public String toString() {
return "Consumer: tag=[" + (consumer != null ? consumer.getConsumerTag() : null) + "], channel=" + channel
+ ", acknowledgeMode=" + acknowledgeMode + " local queue size=" + queue.size();
}
/**
* Perform a rollback, handling rollback exceptions properly.
* @param ex the thrown application exception or error
* @throws Exception in case of a rollback error
*/
public void rollbackOnExceptionIfNecessary(Throwable ex) throws Exception {
boolean ackRequired = !acknowledgeMode.isAutoAck() && !acknowledgeMode.isManual();
try {
if (transactional) {
if (logger.isDebugEnabled()) {
logger.debug("Initiating transaction rollback on application exception: " + ex);
}
RabbitUtils.rollbackIfNecessary(channel);
}
if (ackRequired) {
if (logger.isDebugEnabled()) {
logger.debug("Rejecting messages");
}
boolean shouldRequeue = this.defaultRequeuRejected;
Throwable t = ex;
while (shouldRequeue && t != null) {
if (t instanceof AmqpRejectAndDontRequeueException) {
shouldRequeue = false;
}
t = t.getCause();
}
for (Long deliveryTag : deliveryTags) {
// With newer RabbitMQ brokers could use basicNack here...
channel.basicReject(deliveryTag, shouldRequeue);
}
if (transactional) {
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
} catch (Exception e) {
logger.error("Application exception overridden by rollback exception", ex);
throw e;
} finally {
deliveryTags.clear();
}
}
/**
* Perform a commit or message acknowledgement, as appropriate.
* @param locallyTransacted
* @throws IOException
*/
public boolean commitIfNecessary(boolean locallyTransacted) throws IOException {
if (deliveryTags.isEmpty()) {
return false;
}
try {
boolean ackRequired = !acknowledgeMode.isAutoAck() && !acknowledgeMode.isManual();
if (ackRequired) {
if (transactional && !locallyTransacted) {
// Not locally transacted but it is transacted so it
// could be synchronized with an external transaction
for (Long deliveryTag : deliveryTags) {
ConnectionFactoryUtils.registerDeliveryTag(connectionFactory, channel, deliveryTag);
}
} else {
if (!deliveryTags.isEmpty()) {
long deliveryTag = new ArrayList<Long>(deliveryTags).get(deliveryTags.size() - 1);
channel.basicAck(deliveryTag, true);
}
}
}
if (locallyTransacted) {
// For manual acks we still need to commit
RabbitUtils.commitIfNecessary(channel);
}
} finally {
deliveryTags.clear();
}
return true;
}
}