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
        }
    }
}

在上面的代码(取自Redigo doc)中,如果连接丢失,所有订阅也将丢失。从丢失的连接中恢复并重新订阅的更好方法是什么。

最佳答案

使用两个嵌套循环。外部循环获取连接,设置订阅,然后调用内部循环以接收消息。内部循环一直执行到连接上出现永久性错误为止。

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()
}

本示例使用Redigo pool获取连接。另一种方法是直接拨打连接:
 c, err := redis.Dial("tcp", serverAddress)

10-08 04:44