如何在 Golang 中为 Redis(redigo) Pubsub 编写更好的 Receive()?
How to write better Receive() in Golang for Redis(redigo) Pubsub?
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),如果连接丢失,所有订阅也会丢失。从丢失的连接中恢复并重新订阅的更好方法是什么。
使用两个嵌套循环。外循环获取连接,设置订阅,然后调用内循环来接收消息。内部循环一直执行到连接出现永久性错误为止。
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)
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),如果连接丢失,所有订阅也会丢失。从丢失的连接中恢复并重新订阅的更好方法是什么。
使用两个嵌套循环。外循环获取连接,设置订阅,然后调用内循环来接收消息。内部循环一直执行到连接出现永久性错误为止。
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)