loading...

How to publish a message with priority in RabbitMQ

hardiksondagar profile image Hardik Sondagar ・1 min read

Dependencies

  • RabbitMQ (>=3.5.0)
  • Python 3.6
  • Pika

In this article, we will learn how to publish and consume messages with priority in RabbitMQ. We will be using python language and pika library for AMQP.

Here we are declaring queue with x-max-priority argument. This argument is integer number from 0 to 255. It describes that the queue can accept messages with max priority equal to this number.

import pika

queue_name = 'priority-queue'
max_priority = 10

# connect and get channel
parameters = pika.ConnectionParameters('localhost')
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# declare queue with max priority
channel.queue_declare(
    queue=queue_name, arguments={"x-max-priority": max_priority}
)

Publish messages with different priorities.

def publish(message, priority)
    message = message + str(priority)
    channel.basic_publish(
        properties=pika.BasicProperties(priority=priority),
        exchange='',
        routing_key=queue_name,
        body=message
    )
# message with priority 0
message = 'message-with-priority-'
publish(message, 0)
# message with priority 5
publish(message, 5)

Now consume messages from the queue and find that message with higher priority will be consumed first even if it was published later.

method_frame, header_frame, body = channel.basic_get(queue_name)
print(body)
# message-with-priority-5
method_frame, header_frame, body = channel.basic_get(queue_name)
print(body)
# message-with-priority-0

Source Code : rabbitmq-priority-queue-example

Discussion

pic
Editor guide