如何在Golang中为Redis(redigo)Pubsub写更好的Receive()?

kic*_*kic -1 go publish-subscribe redis redigo

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Cer*_*món 5

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

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()
}
Run Code Online (Sandbox Code Playgroud)

此示例使用Redigo 来获取连接.另一种方法是直接拨打连接:

 c, err := redis.Dial("tcp", serverAddress)
Run Code Online (Sandbox Code Playgroud)