Set the Number of Reconnect Attempts

Applications can set the maximum reconnect attempts per server. This includes the server provided to the client’s connect call, as well as the server the client discovered through another server. Once reconnect to a server fails the specified amount of times in a row, it will be removed from the connect list. After a successful reconnect to a server, the client will reset that server’s failed reconnect attempt count. If a server was removed from the connect list, it can be rediscovered on connect. This effectively resets the connect attempt count as well. If the client runs out of servers to reconnect, it will close the connection and raise an error.

{% tabs %} {% tab title=”Go” %}

  1. // Set max reconnects attempts
  2. nc, err := nats.Connect("demo.nats.io", nats.MaxReconnects(10))
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer nc.Close()
  7. // Do something with the connection

{% endtab %}

{% tab title=”Java” %}

  1. Options options = new Options.Builder().
  2. server("nats://demo.nats.io:4222").
  3. maxReconnects(10). // Set max reconnect attempts
  4. build();
  5. Connection nc = Nats.connect(options);
  6. // Do something with the connection
  7. nc.close();

{% endtab %}

{% tab title=”JavaScript” %}

  1. const nc = await connect({
  2. maxReconnectAttempts: 10,
  3. servers: ["demo.nats.io"],
  4. });

{% endtab %}

{% tab title=”Python” %}

  1. nc = NATS()
  2. await nc.connect(
  3. servers=["nats://demo.nats.io:4222"],
  4. max_reconnect_attempts=10,
  5. )
  6. # Do something with the connection
  7. await nc.close()

{% endtab %}

{% tab title=”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"], max_reconnect_attempts: 10) do |nc|
  3. # Do something with the connection
  4. # Close the connection
  5. nc.close
  6. end

{% endtab %}

{% tab title=”C” %}

  1. natsConnection *conn = NULL;
  2. natsOptions *opts = NULL;
  3. natsStatus s = NATS_OK;
  4. s = natsOptions_Create(&opts);
  5. if (s == NATS_OK)
  6. s = natsOptions_SetMaxReconnect(opts, 10);
  7. if (s == NATS_OK)
  8. s = natsConnection_Connect(&conn, opts);
  9. (...)
  10. // Destroy objects that were created
  11. natsConnection_Destroy(conn);
  12. natsOptions_Destroy(opts);

{% endtab %} {% endtabs %}