Setting a Connect Timeout
Each library has its own, language preferred way, to pass connection options. One of the most common options is a connect timeout. It limits how long it can take to establish a connection to a server. Should multiple URLs be provided, this timeout applies to each cluster member individually. To set the maximum time to connect to a server to 10 seconds:
Go
Java
JavaScript
Python
Ruby
C
1
nc, err := nats.Connect("demo.nats.io", nats.Name("API Options Example"), nats.Timeout(10*time.Second))
2
if err != nil {
3
log.Fatal(err)
4
}
5
defer nc.Close()
6
7
// Do something with the connection
Copied!
1
Options options = new Options.Builder().
2
server("nats://demo.nats.io:4222").
3
connectionTimeout(Duration.ofSeconds(10)). // Set timeout
4
build();
5
Connection nc = Nats.connect(options);
6
7
// Do something with the connection
8
9
nc.close();
Copied!
1
const nc = await connect({
2
reconnectTimeWait: 10 * 1000, // 10s
3
servers: ["demo.nats.io"],
4
});
Copied!
1
nc = NATS()
2
await nc.connect(
3
servers=["nats://demo.nats.io:4222"],
4
connect_timeout=10)
5
6
# Do something with the connection
7
8
await nc.close()
Copied!
1
# There is currently no connect timeout as part of the Ruby NATS client API, but you can use a timer to mimic it.
2
require 'nats/client'
3
4
timer = EM.add_timer(10) do
5
NATS.connect do |nc|
6
# Do something with the connection
7
8
# Close the connection
9
nc.close
10
end
11
end
12
EM.cancel_timer(timer)
Copied!
1
nnatsConnection *conn = NULL;
2
natsOptions *opts = NULL;
3
natsStatus s = NATS_OK;
4
5
s = natsOptions_Create(&opts);
6
if (s == NATS_OK)
7
// Set the timeout to 10 seconds (10,000 milliseconds)
8
s = natsOptions_SetTimeout(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!
Export as PDF
Copy link
Edit on GitHub