Commits

Chad Burrus  committed 9234a9c

tutorial 5

  • Participants
  • Parent commits a0363cf

Comments (0)

Files changed (2)

File tut5/emit_logs.py

+#!/usr/bin/env python
+import pika
+import sys
+
+# make connection to RabbitMQ server
+connection = pika.BlockingConnection(pika.ConnectionParameters(
+                 'localhost'))
+channel = connection.channel()
+
+# make an exchange that will pass log information to everyone
+channel.exchange_declare(exchange='topic_logs', type='topic')
+
+# Send the message
+routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
+message = ' '.join(sys.argv[2:]) or 'Hello World!'
+channel.basic_publish(exchange='topic_logs',
+                      routing_key=routing_key,
+                      body=message)
+
+# Print a handy message
+print " [x] Sent %s:%s " % (routing_key, message)
+
+# Close up shop, flushing buffers and the like
+connection.close()

File tut5/receive_logs.py

+#!/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()