Below are python examples for message producer and message consumer
The script to produce messages:
#!/usr/bin/python
import pika
import sys
credentials = pika.PlainCredentials("guest", "guest")
conn_params = pika.ConnectionParameters("localhost",
credentials = credentials)
conn_broker = pika.BlockingConnection(conn_params)
channel = conn_broker.channel()
channel.exchange_declare(exchange="hello-exchange",
exchange_type="direct",
passive=False,
durable=True,
auto_delete=False)
msg = sys.argv[1]
msg_props = pika.BasicProperties()
msg_props.content_type = "text/plain"
channel.basic_publish(body=msg,
exchange="hello-exchange",
properties=msg_props,
routing_key="hola")
The script creates channel to rabbitmq located on localhost under default "guest" user, created direct exchange and routing key and finally puplishes message taken from first argument.
The script to create queue and to subscribe to exchange:
#!/usr/bin/python
import pika
import sys
credentials = pika.PlainCredentials("guest", "guest")
conn_params = pika.ConnectionParameters("localhost",
credentials = credentials)
conn_broker = pika.BlockingConnection(conn_params)
channel = conn_broker.channel()
channel.exchange_declare(exchange="hello-exchange",
exchange_type="direct",
passive=False,
durable=True,
auto_delete=False)
channel.queue_declare(queue="hello-queue")
channel.queue_bind(queue="hello-queue",
exchange="hello-exchange",
routing_key="hola")
def msg_consumer(channel, method, header, body):
channel.basic_ack(delivery_tag=method.delivery_tag)
if body == "quit":
channel.basic_cancel(consumer_tag="hello-consumer")
channel.stop_consuming()
else:
print body
return
channel.basic_consume(on_message_callback=msg_consumer,
queue="hello-queue",
consumer_tag="hello-consumer")
channel.start_consuming()
The code above was successfully tested on Python 2.7.12 and pika 1.1.0.