Skip to content

Instantly share code, notes, and snippets.

@kumar-de
Last active April 19, 2020 21:03
Show Gist options
  • Save kumar-de/b8feb2f99dd87991c5a76aedae749818 to your computer and use it in GitHub Desktop.
Save kumar-de/b8feb2f99dd87991c5a76aedae749818 to your computer and use it in GitHub Desktop.
RabbitMQ - quick setup and pythonic producer/consumer examples #rabbitmq #quick #setup #python #examples #producer #consumer

Install RabbitMQ on Docker (with management console)

docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management

Install Pika library

pip3 install pika

Pythonic Producer - send.py

#!/usr/bin/env python
import pika

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

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

Pythonic Consumer - receive.py

#!/usr/bin/env python
import pika

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

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(properties)
    print(" [x] Received %r" % body)

channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

Run send/receive scripts

python3 send.py
python3 receive.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment