This code create a producer which send two messages to a queue, and a consumer which receives all the messages from that queue.
Code for producer.py (using the pika 0.10.0 Python client):
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='queueName')
channel.basic_publish(exchange='',
routing_key='queueName',
body='Hello')
channel.basic_publish(exchange='',
routing_key='queueName',
body='World!')
print("Message sent")
connection.close()
Code for consumer.py:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='queueName')
def callback(ch, method, properties, body):
print("Received message: %r" % body)
channel.basic_consume(callback,
queue='queueName',
no_ack=True)
print('Waiting for messages...')
channel.start_consuming()
The output is:
$ python receive.py
Waiting for messages...
Received message: 'Hello'
Received message: 'World!'
Other examples are available in the RabbitMQ tutorial page for other languages.