Connecting to a Cluster
- Passing a URL for each cluster member (semi-optional)
- The connection algorithm
- The reconnect algorithm (discussed later)
- Server provided URLs
When a client library first tries to connect it will use the list of URLs provided to the connection options or function. These URLs are usually checked in random order as to not have every client connect to the same server. The first successful connection is used. Randomization can be explicitly disabled.
After a client connects to the server, the server may provide a list of URLs for additional known servers. This allows a client to connect to one server and still have other servers available during reconnect.
To ensure the initial connection, your code should include a list of reasonable front line or seed servers. Those servers may know about other members of the cluster, and may tell the client about those members. But you don’t have to configure the client to pass every valid member of the cluster in the connect method.
Note, failure behavior is library dependent, please check the documentation for your client library on information about what happens if the connect fails.
Go
Java
server("nats://localhost:1222").
server("nats://localhost:1223").
server("nats://localhost:1224").
build();
Connection nc = Nats.connect(options);
nc.close();
Python
await nc.connect(servers=[
"nats://127.0.0.1:1222",
"nats://127.0.0.1:1223",
"nats://127.0.0.1:1224"
])
# Do something with the connection
Ruby
TypeScript
let nc = await connect({
servers: [
"nats://demo.nats.io:4222",
"nats://localhost:4222"
]
});
// Do something with the connection
// When done close it