Priority queues

更新时间:
复制 MD 格式

Priority queues deliver higher-priority messages before lower-priority ones. When messages accumulate, the queue reorders them by priority value instead of using the default FIFO order, so that critical work is processed first.

How it works

In a standard queue, messages are delivered in arrival order (FIFO). A priority queue reorders pending messages so that higher-priority messages are delivered first.

Consider three messages published to a queue:

MessageEnqueue orderPriority
A11
B23
C32

A standard queue delivers them in FIFO order: A, B, C. A priority queue delivers them by priority: B, C, A.

Priority reordering only applies to messages waiting in the queue. If a consumer is connected and the queue is empty, each message is delivered immediately on arrival -- no reordering occurs.

To make priority take effect, set a basic.qos (prefetch) limit on consumers so that messages accumulate in the queue and can be reordered.

Prerequisites

Before you begin, make sure that you have:

  • A dedicated instance of ApsaraMQ for RabbitMQ (priority queues are not available on shared instances)

  • An approved support ticket to enable priority queues -- submit a ticket

Declare a priority queue

Declare a priority queue on the client by setting the x-max-priority argument. The value defines the maximum priority level and must be an integer from 1 to 10.

Channel ch = ...;
Map<String, Object> args = new HashMap<String, Object>();
// Set the maximum priority level (valid range: 1-10)
args.put("x-max-priority", 10);
ch.queueDeclare("my-priority-queue", true, false, false, args);

After declaring the queue, publish prioritized messages using the priority field of basic.properties. Larger values indicate higher priority.

// Publish a message with priority 5
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
        .priority(5)
        .build();
ch.basicPublish("", "my-priority-queue", props, "high priority task".getBytes());

Replace the following placeholders with your actual values:

PlaceholderDescriptionExample
my-priority-queueQueue nameorder-processing-priority

Behavior and best practices

  • Consumer prefetch matters. If basic.qos (prefetch) is set too high, the consumer's prefetch buffer fills with lower-priority messages before higher-priority messages arrive. Use a smaller prefetch value to give the queue more opportunity to reorder by priority.

  • Priority only applies to pending messages. If the queue is empty and a consumer is waiting, messages are delivered immediately regardless of priority.

Limitations

LimitationDetails
Priority range1 to 10
Immutable after declarationThe x-max-priority value cannot be changed after the queue is declared. To use a different maximum priority, declare a new queue.
Instance typeAvailable only on dedicated instances

What's next