/examples/receive_log_direct.py

https://github.com/elastic-coders/aioamqp · Python · 53 lines · 32 code · 13 blank · 8 comment · 4 complexity · dbb75244144c53982530e87e43111a37 MD5 · raw file

  1. #!/usr/bin/env python
  2. """
  3. Rabbitmq.com pub/sub example
  4. https://www.rabbitmq.com/tutorials/tutorial-four-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 = 'direct_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, 'direct')
  25. yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)
  26. severities = sys.argv[1:]
  27. if not severities:
  28. print("Usage: %s [info] [warning] [error]" % (sys.argv[0],))
  29. sys.exit(1)
  30. for severity in severities:
  31. yield from asyncio.wait_for(channel.queue_bind(exchange_name='direct_logs',
  32. queue_name=queue_name,
  33. routing_key=severity), 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. yield from asyncio.Event().wait()
  37. loop = asyncio.get_event_loop()
  38. loop.run_until_complete(receive_log())