在 Go 中重新连接到 Redis 订阅的惯用方法是什么?

What's an idiomatic way to reconnect to Redis subscription in Go?

我正在使用 redigo 库尝试订阅 Redis 频道,然后处理已发布的消息。 我如何处理它出错的情况? 这是我想出的。这是一个好方法吗?有没有更好的方法?

注意:这个问题是redigo特有的,但我认为它适用于其他需要重新连接的地方。

package main

import (
    "fmt"
    "time"

    "github.com/garyburd/redigo/redis"
)

func main() {
    for {
        fmt.Println("connecting...")
        c, err := redis.Dial("tcp", "localhost:6379")
        if err != nil {
            fmt.Println("error connecting to redis")
            time.Sleep(5 * time.Second)
            continue
        }
        psc := redis.PubSubConn{c}
        psc.Subscribe("example")
    ReceiveLoop:
        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:
                fmt.Println("there was an error")
                fmt.Println(v)
                time.Sleep(5 * time.Second)
                break ReceiveLoop
            }
        }
    }
}

为了示例,我只是将它放在 main() 函数中。在某些 goroutine 中确实会 运行。

是的,使用标签和循环是重新连接的标准做法。

您唯一缺少的是关闭连接。

            psc.Close()
            break ReceiveLoop

为了更有弹性,您可能需要 redis.DialTimeout 这样 Dial 呼叫就不会无限期地挂起。