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

我正在使用 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 中运行。


慕村225694
浏览 298回答 1
1回答

绝地无双

是的,使用标签和循环是重新连接的标准做法。您唯一缺少的是关闭连接。            psc.Close()                         break ReceiveLoop为了增加一点弹性,您可能希望redis.DialTimeout拨号呼叫不能无限期挂起。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go