Search code examples
goredispublish-subscriberedigo

How to write better Receive() in Golang for Redis(redigo) Pubsub?


psc := redis.PubSubConn{c}
psc.Subscribe("example")

func Receive() {
    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
        case error:
            return v
        }
    }
}

In the above code(taken from Redigo doc), if connection is lost, all subscriptions are also lost. What will be better way to recover from lost connection and resubscribe.


Solution

  • Use two nested loops. The outer loop gets a connection, sets up the subscriptions and then invokes the inner loop to receive messages. The inner loop executes until there's a permanent error on the connection.

    for {
        // Get a connection from a pool
        c := pool.Get()
        psc := redis.PubSubConn{c}
    
        // Set up subscriptions
        psc.Subscribe("example"))
    
        // While not a permanent error on the connection.
        for c.Err() == nil {
            switch v := psc.Receive().(type) {
            case redis.Message:
                fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
            case redis.Subscription:
                fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
            case error:
                fmt.Printf(err)
            }
        }
        c.Close()
    }
    

    This example uses a Redigo pool to get connections. An alternative is to dial a connection directly:

     c, err := redis.Dial("tcp", serverAddress)