2015-10-17 145 views
-1
psc := redis.PubSubConn{c} 
psc.Subscribe("example") 

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

在上面的代码中(取自Redigo doc),如果连接丢失,所有订阅也会丢失。什么是更好的方式来恢复丢失的连接和重新订阅。如何在Redlang(redigo)Pubsub中更好地编写Golang中的Receive()?

+0

如何创建['redis.Pool'(https://godoc.org/github.com/garyburd/redigo/redis#Pool),其'拨号'功能也订阅适当的渠道。 –

+0

@ tim-cooper很干净的方式。 +1 – kic

回答

3

使用两个嵌套循环。外部循环获取连接,设置订阅,然后调用内部循环接收消息。执行内部循环,直到连接出现永久性错误。

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\n", v.Channel, v.Data) 
     case redis.Subscription: 
      fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count) 
     case error: 
      fmt.Printf(err) 
     } 
    } 
    c.Close() 
} 

本示例使用Redigo pool来获取连接。另一种方法是直接拨号连接:

c, err := redis.Dial("tcp", serverAddress) 
+0

非常感谢。很好的解决方案,适合我! – kic

+0

Tim Cooper的评论解决方案更加清晰。拨号在重新连接期间负责订阅。感谢+1 – kic

+0

@ aloksrivastava78通过拨号预订防止在应用程序中将其用于其他用途,将订阅代码从接收代码移开得更远,并且每个redigo文档都不允许使用该代码。 –