doufuhuang6981
2015-05-01 13:31
浏览 296

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

I am using the redigo library to try to subscribe to a Redis channel and then handle a published message. How do I handle the case where it errors out? Here's what I came up with. Is this a good way to do it? Is there a better way?

Note: this question is specific to redigo, but I think it applies to other places where reconnections need to happen.

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
", v.Channel, v.Data)
            case redis.Subscription:
                fmt.Printf("%s: %s %d
", v.Channel, v.Kind, v.Count)
            case error:
                fmt.Println("there was an error")
                fmt.Println(v)
                time.Sleep(5 * time.Second)
                break ReceiveLoop
            }
        }
    }
}

I just put it in the main() function for the example. It would really run in some goroutine.

图片转代码服务由CSDN问答提供 功能建议

我正在使用Redigo库尝试订阅Redis频道,然后处理已发布的消息。 如何做 如果出现错误,我可以解决吗? 这就是我的想法。 这是一个好方法吗? 有没有更好的方法?

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

  package main 
 
import(
“ fmt” 
“ time” 
 
“ github.com/garyburd/redigo/redis"
)

func main(){
为 {
 fmt.Println(“ connecting ...”)
c,err:= redis.Dial(“ tcp”,“ localhost:6379”)
如果err!= nil {
 fmt.Println(“ error 连接到redis“)
 time.Sleep(5 * time.Second)
继续
} 
 psc:= redis.PubSubConn {c} 
 psc.Subscribe(” example“)
 ReceiveLoop:
 对于{
开关v:= psc.Receive()。(类型){
 case redis.Message:
 fmt.Printf(“%s:message:%s 
”,v.Channel,v.Data  )
 case redis。订阅:
 fmt.Printf(“%s:%s%d 
”,v.Channel,v.Kind,v.Count)
 case错误:
 fmt.Println(“ 发生错误“)
 fmt.Printl  n(v)
 time.Sleep(5 * time.Second)
 break ReceiveLoop 
} 
} 
} 
} 
   
 
 

I 只需将其放在示例的main()函数中即可。 确实可以在某些goroutine中运行。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpl3350 2015-05-01 19:29
    已采纳

    Yes, using a label and a loop is standard practice for reconnecting.

    The only thing you're missing is closing the connection.

                psc.Close()
                break ReceiveLoop
    

    For a little more resilience, you may want redis.DialTimeout so that a Dial call can't hang indefinitely.

    打赏 评论

相关推荐 更多相似问题