reconnect_event.py 778 B

123456789101112131415161718192021222324252627282930313233343536
  1. import asyncio
  2. from nats.aio.client import Client as NATS
  3. async def example():
  4. # [begin reconnect_event]
  5. nc = NATS()
  6. async def disconnected_cb():
  7. print("Got disconnected!")
  8. async def reconnected_cb():
  9. # See who we are connected to on reconnect.
  10. print("Got reconnected to {url}".format(url=nc.connected_url.netloc))
  11. await nc.connect(
  12. servers=["nats://demo.nats.io:4222"],
  13. reconnect_time_wait=10,
  14. reconnected_cb=reconnected_cb,
  15. disconnected_cb=disconnected_cb,
  16. )
  17. # Do something with the connection.
  18. # [end reconnect_event]
  19. while True:
  20. if nc.is_closed:
  21. break
  22. await asyncio.sleep(1)
  23. await nc.close()
  24. loop = asyncio.get_event_loop()
  25. loop.run_until_complete(example())
  26. loop.close()