redigo golang客户端是否支持密钥空间事件通知?

时间:2016-03-31 19:53:16

标签: go redigo

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

1 个答案:

答案 0 :(得分:7)

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

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
    }
}
相关问题