broker/nats.Connect: avoid conn leaks

This commit is contained in:
maru 2019-03-13 19:58:19 +08:00 committed by Vasiliy Tolstov
parent ae10eb2ab8
commit 29bf388131

20
nats.go
View File

@ -88,13 +88,18 @@ func setAddrs(addrs []string) []string {
}
func (n *nbroker) Connect() error {
n.RLock()
if n.conn != nil && n.conn.IsConnected() {
n.RUnlock()
return nil
}
n.RUnlock()
n.Lock()
defer n.Unlock()
status := nats.CLOSED
if n.conn != nil {
status = n.conn.Status()
}
switch status {
case nats.CONNECTED, nats.RECONNECTING, nats.CONNECTING:
return nil
default: // DISCONNECTED or CLOSED or DRAINING
opts := n.nopts
opts.Servers = n.addrs
opts.Secure = n.opts.Secure
@ -109,11 +114,10 @@ func (n *nbroker) Connect() error {
if err != nil {
return err
}
n.Lock()
n.conn = c
n.Unlock()
return nil
}
}
func (n *nbroker) Disconnect() error {
n.RLock()