Powered By GitBook
Pausing Between Reconnect Attempts
It doesn’t make much sense to try to connect to the same server over and over. To prevent this sort of thrashing, and wasted reconnect attempts, especially when using TLS, libraries provide a wait setting. Generally clients make sure that between two reconnect attempts to the same server at least a certain amount of time has passed. The concrete implementation depends on the library used.
This setting not only prevents wasting client resources, it also alleviates a thundering herd situation when additional servers are not available.
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
// Set reconnect interval to 10 seconds
2
nc, err := nats.Connect("demo.nats.io", nats.ReconnectWait(10*time.Second))
3
if err != nil {
4
log.Fatal(err)
5
}
6
defer nc.Close()
7
8
// Do something with the connection
Copied!
1
Options options = new Options.Builder().
2
server("nats://demo.nats.io:4222").
3
reconnectWait(Duration.ofSeconds(10)). // Set Reconnect Wait
4
build();
5
Connection nc = Nats.connect(options);
6
7
// Do something with the connection
8
9
nc.close();
Copied!
1
let nc = NATS.connect({
2
servers: ["nats://demo.nats.io:4222"]
3
});
Copied!
1
nc = NATS()
2
await nc.connect(
3
servers=["nats://demo.nats.io:4222"],
4
reconnect_time_wait=10,
5
)
6
7
# Do something with the connection
8
9
await nc.close()
Copied!
1
require 'nats/client'
2
3
NATS.start(servers: ["nats://127.0.0.1:1222", "nats://127.0.0.1:1223", "nats://127.0.0.1:1224"], reconnect_time_wait: 10) do |nc|
4
# Do something with the connection
5
6
# Close the connection
7
nc.close
8
end
Copied!
1
// will throw an exception if connection fails
2
let nc = await connect({
3
servers: ["nats://demo.nats.io:4222"]
4
});
5
nc.close();
Copied!
1
natsConnection *conn = NULL;
2
natsOptions *opts = NULL;
3
natsStatus s = NATS_OK;
4
5
s = natsOptions_Create(&opts);
6
if (s == NATS_OK)
7
// Set reconnect interval to 10 seconds (10,000 milliseconds)
8
s = natsOptions_SetReconnectWait(opts, 10000);
9
if (s == NATS_OK)
10
s = natsConnection_Connect(&conn, opts);
11
12
(...)
13
14
// Destroy objects that were created
15
natsConnection_Destroy(conn);
16
natsOptions_Destroy(opts);
Copied!
Last modified 1yr ago
Export as PDF
Copy link