/examples/receive_log.py

https://github.com/elastic-coders/aioamqp · Python · 45 lines · 22 code · 15 blank · 8 comment · 2 complexity · c59d0217b7b937a1f12ef989fa2ab385 MD5 · raw file

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