Theory: http://rabbitmq.mr-ping.com/tutorials_with_python/[1]Hello_World.html
Bring the code together
Complete code of 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()
Complete code of 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(" [x] Received %r" % body)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
Now we can try our program in the terminal.
First we start a consumer that will keep running waiting for deliveries to arrive.
python receive.py
# => [*] Waiting for messages. To exit press CTRL+C
# => [x] Received 'Hello World!'
Then start the producer, the producer program will stop running after each execution.
python send.py
# => [x] Sent 'Hello World!'
It worked! We have sent our first message via RabbitMQ. As you may have noticed, the receive.py program does not exit. It has been preparing to get messages, you can abort it with Ctrl-C.