我正在使用 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
拨号呼叫不能无限期挂起。
- 1 回答
- 0 关注
- 297 浏览
添加回答
举报
0/150
提交
取消