Here we are using pika
python
client. You can pick anyone as per your application.
Find the list of clients here
RabbitMQ
is installed and is running on localhost. You can simply do this by running docker image :
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.12-management
Pika Client
pip install pika --upgrade
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 actually delivered to RabbitMQ. We can do it by gently closing the connection.
connection.close()
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)
Run Consumer
python receiver.py
Run Producer
python sender.py
By, Consumer
# => [*] Waiting for messages. To exit press CTRL+C
# => [x] Received 'Hello World!'
Unravel the secrets of RabbitMQ with our reference to the original RabbitMQ tutorial here.
With this guide, you’ve taken the first step into a world of endless possibilities. Stay tuned for more advanced programs