Source

rabbitmq-tutorials / tut5 / receive_logs.py

Full commit
#!/usr/bin/env python
import pika
import sys

# make connection to RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

# make an exchange that will pass log information to everyone
channel.exchange_declare(exchange='topic_logs', type='topic')

# init a random queue so we don't get any old messages, and make sure it's nuked when the consumer dies?  
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

# add in the desired binding_keys
binding_keys = sys.argv[1:]
if not binding_keys:
  print >>sys.stderr, "Usage: %s [binding_key]..." % sys.argv[0]
  sys.exit(1)

for binding_key in binding_keys:
  # bind the new anonymous queue to the logs exchange so it can receive messages
  channel.queue_bind(exchange='topic_logs', queue=queue_name, routing_key=binding_key)

# Print a handy message
print ' [*] Waiting for logs. To exit press CTRL+C'

# The thing to do when a message is received
def callback(ch, method, properties, body):
  print " [x] %r:%r" % (method.routing_key, body,)

# Set up the consumer
channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

# Start consuming
channel.start_consuming()