subscribe_async.py 615 B

12345678910111213141516171819202122232425262728293031
  1. import asyncio
  2. from nats.aio.client import Client as NATS
  3. async def example():
  4. # [begin subscribe_async]
  5. nc = NATS()
  6. await nc.connect(servers=["nats://demo.nats.io:4222"])
  7. future = asyncio.Future()
  8. async def cb(msg):
  9. nonlocal future
  10. future.set_result(msg)
  11. await nc.subscribe("updates", cb=cb)
  12. await nc.publish("updates", b'All is Well')
  13. await nc.flush()
  14. # Wait for message to come in
  15. msg = await asyncio.wait_for(future, 1)
  16. # [end subscribe_async]
  17. print(msg)
  18. await nc.close()
  19. loop = asyncio.get_event_loop()
  20. loop.run_until_complete(example())
  21. loop.close()