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 { func (n *nbroker) Connect() error {
n.RLock() n.Lock()
if n.conn != nil && n.conn.IsConnected() { defer n.Unlock()
n.RUnlock()
return nil
}
n.RUnlock()
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 := n.nopts
opts.Servers = n.addrs opts.Servers = n.addrs
opts.Secure = n.opts.Secure opts.Secure = n.opts.Secure
@ -109,10 +114,9 @@ func (n *nbroker) Connect() error {
if err != nil { if err != nil {
return err return err
} }
n.Lock()
n.conn = c n.conn = c
n.Unlock()
return nil return nil
}
} }
func (n *nbroker) Disconnect() error { func (n *nbroker) Disconnect() error {