关注重连事件
Because reconnect is primarily under the covers, many libraries provide an event listener you can use to be notified of reconnect events. This event can be especially important for applications sending a lot of messages.
// Connection event handlers are invoked asynchronously
// and the state of the connection may have changed when
// the callback is invoked.
nc, err := nats.Connect("demo.nats.io",
nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
// handle disconnect error event
}),
nats.ReconnectHandler(func(nc *nats.Conn) {
// handle reconnect event
}))
if err != nil {
log.Fatal(err)
}
defer nc.Close()
// Do something with the connectionOptions options = new Options.Builder().
server("nats://demo.nats.io:4222").
connectionListener((conn, type) -> {
if (type == Events.RECONNECTED) {
// handle reconnected
} else if (type == Events.DISCONNECTED) {
// handle disconnected, wait for reconnect
}
}).
build();
Connection nc = Nats.connect(options);
// Do something with the connection
nc.close();最后更新于