DEV Community

Hardik Sondagar
Hardik Sondagar

Posted on

8 2

How to publish a message with priority in RabbitMQ

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}
)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Source Code : rabbitmq-priority-queue-example

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more