go - redigo golang 客户端是否支持键空间事件通知?

标签 go redigo

我正在使用 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/

相关文章:

google-app-engine - Google App Engine Golang 没有这样的文件或目录

parsing - 使用 jwt-go 库 - key 无效或类型无效

go - Redigo Redis Pool 真的应该是一个全局变量吗?

go - 在结构的字段上实现 Redigo Scanner 接口(interface)

go - 是否有任何自动增量机制用于使用 redigo 包装器将键值存储在 redis 中?

go - 为什么 Golang 包必须是 v0 或 v1 而不是 v2020

mongodb - 如何使用 golang 和 mongodb 过滤日期?

go - 使用gocql的cassandra查询中的可变参数

go - redigo 和 gob 如何检索 gob 数据 slice

go - Redigo:当 Redis 服务器关闭时快速失败