6

我正在使用redigo 库在 golang 中对 redis 客户端进行原型设计,以获取键空间事件的通知。我修改了 redis.conf 以将 notify-keyspace-events 设置为“KEA”以接收所有事件。但是,当我使用 cli 将密钥添加/更新/删除到数据库中时,我看不到任何事件在客户端上被触发。

使用 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 是否支持键空间事件通知?我可能在这里做错了什么?

4

1 回答 1

10

删除订阅模式中的额外引号:

psc.PSubscribe("__key*__:*")

此外,您不需要 goroutines。写成这样更简单:

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
    }
}
于 2016-03-31T20:19:02.537 回答