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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置