2015-10-17 92 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文檔都不允許使用該代碼。 –