0
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),如果连接丢失,所有订阅也会丢失。从丢失的连接中恢复并重新订阅的更好方法是什么。

4

1 回答 1

8

使用两个嵌套循环。外循环获得一个连接,建立订阅,然后调用内循环来接收消息。内部循环一直执行,直到连接出现永久性错误。

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来获取连接。另一种方法是直接拨打连接:

 c, err := redis.Dial("tcp", serverAddress)
于 2015-10-18T03:26:47.090 回答