我正在使用 redigo library 在 golang 中制作一个 redis 客户端的原型(prototype)获得键空间事件的通知。我修改了 redis.conf 以将 notify-keyspace-events 设置为“KEA”以接收所有事件。但是,当我使用 cli 在数据库中添加/更新/删除 key 时,我没有看到客户端触发任何事件。
使用 redigo 触发事件的示例代码:
type RedisClient struct {
mRedisServer string
mRedisConn redis.Conn
mWg sync.WaitGroup
}
func (rc *RedisClient) Run() {
conn, err := redis.Dial("tcp", ":6379")
if err != nil {
fmt.Println(err)
return
}
rc.mRedisConn = conn
fmt.Println(conn)
rc.mRedisConn.Do("CONFIG", "SET", "notify-keyspace-events", "KEA")
fmt.Println("Set the notify-keyspace-events to KEA")
defer rc.mRedisConn.Close()
rc.mWg.Add(2)
psc := redis.PubSubConn{Conn: rc.mRedisConn}
go func() {
defer rc.mWg.Done()
for {
switch msg := psc.Receive().(type) {
case redis.Message:
fmt.Printf("Message: %s %s\n", msg.Channel, msg.Data)
case redis.PMessage:
fmt.Printf("PMessage: %s %s %s\n", msg.Pattern, msg.Channel, msg.Data)
case redis.Subscription:
fmt.Printf("Subscription: %s %s %d\n", msg.Kind, msg.Channel, msg.Count)
if msg.Count == 0 {
return
}
case error:
fmt.Printf("error: %v\n", msg)
return
}
}
}()
go func() {
defer rc.mWg.Done()
psc.PSubscribe("\"__key*__:*\"")
select {}
}()
rc.mWg.Wait()
}
redigo 是否支持键空间事件通知?我在这里做错了什么吗?
最佳答案
删除订阅模式中的额外引号:
psc.PSubscribe("__key*__:*")
此外,您不需要 goroutine。写成这样更简单:
psc := redis.PubSubConn{Conn: rc.mRedisConn}
psc.PSubscribe("__key*__:*")
for {
switch msg := psc.Receive().(type) {
case redis.Message:
fmt.Printf("Message: %s %s\n", msg.Channel, msg.Data)
case redis.PMessage:
fmt.Printf("PMessage: %s %s %s\n", msg.Pattern, msg.Channel, msg.Data)
case redis.Subscription:
fmt.Printf("Subscription: %s %s %d\n", msg.Kind, msg.Channel, msg.Count)
if msg.Count == 0 {
return
}
case error:
fmt.Printf("error: %v\n", msg)
return
}
}
关于go - redigo golang 客户端是否支持键空间事件通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36342510/