subscribe_arrow.py 772 B

12345678910111213141516171819202122232425262728293031323334
  1. import asyncio
  2. from nats.aio.client import Client as NATS
  3. async def example():
  4. # [begin subscribe_arrow]
  5. nc = NATS()
  6. await nc.connect(servers=["nats://demo.nats.io:4222"])
  7. # Use queue to wait for 4 messages to arrive
  8. queue = asyncio.Queue()
  9. async def cb(msg):
  10. await queue.put(msg)
  11. await nc.subscribe("time.>", 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. await nc.publish("time.C.west", b'C')
  16. await nc.publish("time.D.west", b'D')
  17. for i in range(0, 4):
  18. msg = await queue.get()
  19. print("Msg:", msg)
  20. await nc.close()
  21. # [end subscribe_arrow]
  22. loop = asyncio.get_event_loop()
  23. loop.run_until_complete(example())
  24. loop.close()