我正在使用 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 中运行。
绝地无双
相关分类