Listening for Reconnect Events

Because reconnect is primarily under the covers, many libraries provide an event listener you can use to be notified of reconnect events. This event can be especially important for applications sending a lot of messages.

Go

  1. // Connection event handlers are invoked asynchronously
  2. // and the state of the connection may have changed when
  3. // the callback is invoked.
  4. nc, err := nats.Connect("demo.nats.io",
  5. nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
  6. // handle disconnect error event
  7. }),
  8. nats.ReconnectHandler(func(nc *nats.Conn) {
  9. // handle reconnect event
  10. }))
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. defer nc.Close()
  15. // Do something with the connection

Java

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. connectionListener((conn, type) -> {
  4. if (type == Events.RECONNECTED) {
  5. // handle reconnected
  6. } else if (type == Events.DISCONNECTED) {
  7. // handle disconnected, wait for reconnect
  8. }
  9. }).
  10. build();
  11. Connection nc = Nats.connect(options);
  12. // Do something with the connection
  13. nc.close();

JavaScript

  1. const nc = await connect({
  2. maxReconnectAttempts: 10,
  3. servers: ["demo.nats.io"],
  4. });
  5. (async () => {
  6. for await (const s of nc.status()) {
  7. switch (s.type) {
  8. case Status.Reconnect:
  9. t.log(`client reconnected - ${s.data}`);
  10. break;
  11. default:
  12. }
  13. }
  14. })().then();
  15. });

Python

  1. nc = NATS()
  2. async def disconnected_cb():
  3. print("Got disconnected!")
  4. async def reconnected_cb():
  5. # See who we are connected to on reconnect.
  6. print("Got reconnected to {url}".format(url=nc.connected_url.netloc))
  7. await nc.connect(
  8. servers=["nats://demo.nats.io:4222"],
  9. reconnect_time_wait=10,
  10. reconnected_cb=reconnected_cb,
  11. disconnected_cb=disconnected_cb,
  12. )
  13. # Do something with the connection.

Ruby

  1. require 'nats/client'
  2. NATS.start(servers: ["nats://127.0.0.1:1222", "nats://127.0.0.1:1223", "nats://127.0.0.1:1224"]) do |nc|
  3. # Do something with the connection
  4. nc.on_reconnect do
  5. puts "Got reconnected to #{nc.connected_server}"
  6. end
  7. nc.on_disconnect do |reason|
  8. puts "Got disconnected! #{reason}"
  9. end
  10. end

C

  1. static void
  2. disconnectedCB(natsConnection *conn, void *closure)
  3. {
  4. // Handle disconnect error event
  5. }
  6. static void
  7. reconnectedCB(natsConnection *conn, void *closure)
  8. {
  9. // Handle reconnect event
  10. }
  11. (...)
  12. natsConnection *conn = NULL;
  13. natsOptions *opts = NULL;
  14. natsStatus s = NATS_OK;
  15. s = natsOptions_Create(&opts);
  16. // Connection event handlers are invoked asynchronously
  17. // and the state of the connection may have changed when
  18. // the callback is invoked.
  19. if (s == NATS_OK)
  20. s = natsOptions_SetDisconnectedCB(opts, disconnectedCB, NULL);
  21. if (s == NATS_OK)
  22. s = natsOptions_SetReconnectedCB(opts, reconnectedCB, NULL);
  23. if (s == NATS_OK)
  24. s = natsConnection_Connect(&conn, opts);
  25. (...)
  26. // Destroy objects that were created
  27. natsConnection_Destroy(conn);
  28. natsOptions_Destroy(opts);

{% endtabs %}