Use appendIfNotExists instead of append. Fixed bug when connection loss to server leads to exponential grow of channels and patterns array in PubSub in every reconnect

This commit is contained in:
Sergey Shcherbina 2016-09-29 15:12:35 +05:00
parent bb84d84aea
commit 850045d6a6
1 changed files with 19 additions and 2 deletions

View File

@ -43,7 +43,7 @@ func (c *PubSub) subscribe(redisCmd string, channels ...string) error {
func (c *PubSub) Subscribe(channels ...string) error { func (c *PubSub) Subscribe(channels ...string) error {
err := c.subscribe("SUBSCRIBE", channels...) err := c.subscribe("SUBSCRIBE", channels...)
if err == nil { if err == nil {
c.channels = append(c.channels, channels...) c.channels = appendIfNotExists(c.channels, channels...)
c.nsub += len(channels) c.nsub += len(channels)
} }
return err return err
@ -53,7 +53,7 @@ func (c *PubSub) Subscribe(channels ...string) error {
func (c *PubSub) PSubscribe(patterns ...string) error { func (c *PubSub) PSubscribe(patterns ...string) error {
err := c.subscribe("PSUBSCRIBE", patterns...) err := c.subscribe("PSUBSCRIBE", patterns...)
if err == nil { if err == nil {
c.patterns = append(c.patterns, patterns...) c.patterns = appendIfNotExists(c.patterns, patterns...)
c.nsub += len(patterns) c.nsub += len(patterns)
} }
return err return err
@ -74,6 +74,23 @@ func remove(ss []string, es ...string) []string {
return ss return ss
} }
func appendIfNotExists(ss []string, es ...string) []string {
for _, e := range es {
found := false
for _, s := range ss {
if s == e {
found = true
break
}
}
if !found {
ss = append(ss, e)
}
}
return ss
}
// Unsubscribes the client from the given channels, or from all of // Unsubscribes the client from the given channels, or from all of
// them if none is given. // them if none is given.
func (c *PubSub) Unsubscribe(channels ...string) error { func (c *PubSub) Unsubscribe(channels ...string) error {