publish_with_reply.py 692 B

123456789101112131415161718192021222324252627282930313233
  1. import asyncio
  2. import json
  3. from nats.aio.client import Client as NATS
  4. from nats.aio.utils import new_inbox
  5. async def example():
  6. # [begin publish_with_reply]
  7. nc = NATS()
  8. future = asyncio.Future()
  9. async def sub(msg):
  10. nonlocal future
  11. future.set_result(msg)
  12. await nc.connect(servers=["nats://demo.nats.io:4222"])
  13. await nc.subscribe("time", cb=sub)
  14. unique_reply_to = new_inbox()
  15. await nc.publish_request("time", unique_reply_to, b'')
  16. # Use the response
  17. msg = await asyncio.wait_for(future, 1)
  18. print("Reply:", msg)
  19. # [end publish_with_reply]
  20. await nc.close()
  21. loop = asyncio.get_event_loop()
  22. loop.run_until_complete(example())
  23. loop.close()