DEV Community

Kapil Bhandari
Kapil Bhandari

Posted on

Your First Journey into RabbitMQ with Python

Hello World Program

Here we are using pika python client. You can pick anyone as per your application.

Find the list of clients here

Prerequisites

  1. RabbitMQ is installed and is running on localhost. You can simply do this by running the docker image :
   docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management
Enter fullscreen mode Exit fullscreen mode
  1. Pika Client
pip install pika --upgrade
Enter fullscreen mode Exit fullscreen mode

The Program:

Producer Program - sender.py

import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# INFO: this connects to a broker on the local machine(localhost)

# Creating hello queue

channel.queue_declare(queue="hello")

# INFO: message needs to go through the exchange
# exhange specify exactly to which queue the message should go
# Thus, The queue name needs to be specified in the routing_key parameter:

channel.basic_publish(
    exchange='',
    routing_key='hello',
    body='Hello World')

print("[x] Sent 'Hello World!")


# Before exiting the program we need to make sure the network buffers were flushed and our message was delivered to RabbitMQ. We can do it by gently closing the connection.

connection.close()

Enter fullscreen mode Exit fullscreen mode

Consumer Program - receiver.py

import pika, sys, os


def main():
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='hello')

    # Receiving a message works by subscribing a callback function
    #to a queue  Whenever we receive a message, this callback function is called by the Pika library.

    def callback(ch, method, properties, body):
        print(f" [x] Received {body}")


    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
    #finally, we enter a never-ending loop that waits for data and runs callbacks whenever necessary,
    # and catch KeyboardInterrupt during program shutdown.

    print("[*] Waiting for message. To exit  press Ctrl+C")
    channel.start_consuming()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Enter fullscreen mode Exit fullscreen mode

Running

Run Consumer

python receiver.py
Enter fullscreen mode Exit fullscreen mode

Run Producer

python sender.py
Enter fullscreen mode Exit fullscreen mode

Output

By, Consumer

# => [*] Waiting for messages. To exit press CTRL+C
# => [x] Received 'Hello World!'
Enter fullscreen mode Exit fullscreen mode

Reference

Unravel the secrets of RabbitMQ with our reference to the original RabbitMQ tutorial here.

Conclusion

With this guide, you've taken the first step into a world of endless possibilities.
Stay tuned for more advanced programs

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay