/examples/receive_log_topic.py

https://github.com/elastic-coders/aioamqp · Python · 53 lines · 30 code · 15 blank · 8 comment · 4 complexity · 17f2c85eb062db2abd89212f1830deab MD5 · raw file

  1. #!/usr/bin/env python
  2. """
  3. Rabbitmq.com pub/sub example
  4. https://www.rabbitmq.com/tutorials/tutorial-five-python.html
  5. """
  6. import asyncio
  7. import aioamqp
  8. import random
  9. import sys
  10. @asyncio.coroutine
  11. def callback(body, envelope, properties):
  12. print("consumer {} recved {} ({})".format(envelope.consumer_tag, body, envelope.delivery_tag))
  13. @asyncio.coroutine
  14. def receive_log():
  15. try:
  16. transport, protocol = yield from aioamqp.connect('localhost', 5672)
  17. except aioamqp.AmqpClosedConnection:
  18. print("closed connections")
  19. return
  20. channel = yield from protocol.channel()
  21. exchange_name = 'topic_logs'
  22. # TODO let rabbitmq choose the queue name
  23. queue_name = 'queue-%s' % random.randint(0, 10000)
  24. yield from channel.exchange(exchange_name, 'topic')
  25. yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)
  26. binding_keys = sys.argv[1:]
  27. if not binding_keys:
  28. print("Usage: %s [binding_key]..." % (sys.argv[0],))
  29. sys.exit(1)
  30. for binding_key in binding_keys:
  31. yield from asyncio.wait_for(channel.queue_bind(exchange_name='topic_logs',
  32. queue_name=queue_name,
  33. routing_key=binding_key), timeout=10)
  34. print(' [*] Waiting for logs. To exit press CTRL+C')
  35. yield from asyncio.wait_for(channel.basic_consume(queue_name, callback=callback), timeout=10)
  36. asyncio.get_event_loop().run_until_complete(receive_log())