Skip to content

Instantly share code, notes, and snippets.

@krak3n
Created September 2, 2015 09:26
Show Gist options
  • Save krak3n/e3df23e4f7b2197651dd to your computer and use it in GitHub Desktop.
Save krak3n/e3df23e4f7b2197651dd to your computer and use it in GitHub Desktop.
Fault Tolerant Redis Connections in Go
func (s *subscription) consume() {
for {
client := s.client
// Connect to Redis Pubsub Channel
pubsub := client.PubSub()
err := pubsub.Subscribe(s.channel)
// On error sleep for 1 second, log and continue to the next loop iteration
if err != nil {
log.Errorf("Redis Connection Error: %s", err)
time.Sleep(time.Second)
continue
}
ReceiveLoop: // Inner loop label
for {
msg, err := pubsub.Receive() // recieve a message from the channel
if err != nil {
// On error, close the channel and break out of the loop inner loop
log.Error("Redis Error: %s", err)
pubsub.Close()
break ReceiveLoop
} else {
switch m := msg.(type) { // Switch the mesage type
case *redis.Subscription:
log.Debugf("Subscribed: %s", m.Channel)
case *redis.Message:
// place the messsage on the hub broadcast channel
h.broadcast <- []byte(m.Payload)
case error:
// On error, close the channel and break out of the loop inner loop
log.Errorf("Redis Error: %s", m)
pubsub.Close()
break ReceiveLoop
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment