If a consumer cannot process a message immediately but other consumers can, reject and requeue the message so that another consumer can pick it up. ApsaraMQ for RabbitMQ provides two methods:
basicReject-- rejects a single message.basicNack-- rejects one or more messages in a batch.
Both methods let you choose whether to requeue rejected messages or route them to a dead-letter exchange.
Reject a single message
Use basicReject to reject one message at a time.
Parameters
| Parameter | Type | Description |
|---|---|---|
deliveryTag | long | Unique identifier of the message in the channel. |
requeue | boolean | true -- requeue the message. false -- discard the message or route it to a dead-letter exchange. |
Example
// Set auto-ack to false; basicReject requires manual acknowledgment
channel.basicConsume("test", false, "consumertag", new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
System.out.println("Rejected: " + new String(body, "UTF-8")
+ ", deliveryTag: " + envelope.getDeliveryTag()
+ ", messageId: " + properties.getMessageId());
// Reject this message and requeue it for another consumer
channel.basicReject(envelope.getDeliveryTag(), true);
}
});Reject multiple messages
Use basicNack to reject multiple messages in a single call. This is useful when a consumer needs to release a batch of unprocessed messages back to the queue.
Parameters
| Parameter | Type | Description |
|---|---|---|
deliveryTag | long | Unique identifier of the message in the channel. |
multiple | boolean | true -- reject this message and all earlier unacknowledged messages. false -- reject only this message. |
requeue | boolean | true -- requeue the rejected messages. false -- discard the messages or route them to a dead-letter exchange. |
Example
// Set auto-ack to false; basicNack requires manual acknowledgment
channel.basicConsume("test", false, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
System.out.println("Rejected: " + new String(body, "UTF-8")
+ ", deliveryTag: " + envelope.getDeliveryTag()
+ ", messageId: " + properties.getMessageId());
// Reject all unacknowledged messages up to this one and requeue them
channel.basicNack(envelope.getDeliveryTag(), true, true);
}
});In this example, multiple is set to true and requeue is set to true, so all unacknowledged messages up to and including the specified delivery tag are rejected and placed back in the queue.