Monitoring the Connection
Managing the interaction with the server is primarily the job of the client library but most of the libraries also provide some insight into what is happening under the covers.
For example, the client library may provide a mechanism to get the connection's current status:
Go
Java
JavaScript
Python
Ruby
1
nc, err := nats.Connect("demo.nats.io", nats.Name("API Example"))
2
if err != nil {
3
log.Fatal(err)
4
}
5
defer nc.Close()
6
7
getStatusTxt := func(nc *nats.Conn) string {
8
switch nc.Status() {
9
case nats.CONNECTED:
10
return "Connected"
11
case nats.CLOSED:
12
return "Closed"
13
default:
14
return "Other"
15
}
16
}
17
log.Printf("The connection is %v\n", getStatusTxt(nc))
18
19
nc.Close()
20
21
log.Printf("The connection is %v\n", getStatusTxt(nc))
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
System.out.println("The Connection is: " + nc.getStatus());
4
5
nc.close();
6
7
System.out.println("The Connection is: " + nc.getStatus());
Copied!
1
// you can find out where you connected:
2
t.log(`connected to a nats server version ${nc.info.version}`);
3
4
// or information about the data in/out of the client:
5
const stats = nc.stats();
6
t.log(`client sent ${stats.outMsgs} messages and received ${stats.inMsgs}`);
Copied!
1
nc = NATS()
2
3
await nc.connect(
4
servers=["nats://demo.nats.io:4222"],
5
)
6
7
# Do something with the connection.
8
9
print("The connection is connected?", nc.is_connected)
10
11
while True:
12
if nc.is_reconnecting:
13
print("Reconnecting to NATS...")
14
break
15
await asyncio.sleep(1)
16
17
await nc.close()
18
19
print("The connection is closed?", nc.is_closed)
Copied!
1
NATS.start(max_reconnect_attempts: 2) do |nc|
2
puts "Connect is connected?: #{nc.connected?}"
3
4
timer = EM.add_periodic_timer(1) do
5
if nc.closing?
6
puts "Connection closed..."
7
EM.cancel_timer(timer)
8
NATS.stop
9
end
10
11
if nc.reconnecting?
12
puts "Reconnecting to NATS..."
13
next
14
end
15
end
16
end
Copied!
Last modified 21d ago
Export as PDF
Copy link
Edit on GitHub