dongxie7683 2015-10-17 12:20
浏览 800
已采纳

如何在Golang中为Redis(redigo)Pubsub编写更好的Receive()?

psc := redis.PubSubConn{c}
psc.Subscribe("example")

func Receive() {
    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:
            return v
        }
    }
}

In the above code(taken from Redigo doc), if connection is lost, all subscriptions are also lost. What will be better way to recover from lost connection and resubscribe.

  • 写回答

1条回答 默认 最新

  • douhuan6305 2015-10-18 03:26
    关注

    Use two nested loops. The outer loop gets a connection, sets up the subscriptions and then invokes the inner loop to receive messages. The inner loop executes until there's a permanent error on the connection.

    for {
        // Get a connection from a pool
        c := pool.Get()
        psc := redis.PubSubConn{c}
    
        // Set up subscriptions
        psc.Subscribe("example"))
    
        // While not a permanent error on the connection.
        for c.Err() == nil {
            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.Printf(err)
            }
        }
        c.Close()
    }
    

    This example uses a Redigo pool to get connections. An alternative is to dial a connection directly:

     c, err := redis.Dial("tcp", serverAddress)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题