subscribe_star.py 733 B

12345678910111213141516171819202122232425262728293031323334
  1. import asyncio
  2. from nats.aio.client import Client as NATS
  3. async def example():
  4. # [begin subscribe_star]
  5. nc = NATS()
  6. await nc.connect(servers=["nats://demo.nats.io:4222"])
  7. # Use queue to wait for 2 messages to arrive
  8. queue = asyncio.Queue()
  9. async def cb(msg):
  10. await queue.put_nowait(msg)
  11. await nc.subscribe("time.*.east", cb=cb)
  12. # Send 2 messages and wait for them to come in
  13. await nc.publish("time.A.east", b'A')
  14. await nc.publish("time.B.east", b'B')
  15. msg_A = await queue.get()
  16. msg_B = await queue.get()
  17. print("Msg A:", msg_A)
  18. print("Msg B:", msg_B)
  19. # [end subscribe_star]
  20. await nc.close()
  21. loop = asyncio.get_event_loop()
  22. loop.run_until_complete(example())
  23. loop.close()