为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕村225694 2021-10-04 15:40:44
我正在使用 redigo 库尝试订阅 Redis 频道,然后处理已发布的消息。我如何处理它出错的情况?这是我想出的。这是一个很好的方法吗?有没有更好的办法?注意:这个问题是针对 redigo 的,但我认为它适用于其他需要重新连接的地方。package mainimport (    "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 中运行。
查看完整描述

1 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

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

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

            psc.Close()
                        break ReceiveLoop

为了增加一点弹性,您可能希望redis.DialTimeout拨号呼叫不能无限期挂起。


查看完整回答
反对 回复 2021-10-04

添加回答

代码语言

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信