在 Go 语言中,可以使用第三方库 github.com/go-redis/redis/v8
来监听 Redis 的 key 过期事件。
首先,需要创建一个 Redis 客户端实例:
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
}
接着,可以通过 client.ConfigSet()
方法来设置 Redis 的配置项,以便监听 key 过期事件:
err := client.ConfigSet(context.Background(), "notify-keyspace-events", "Ex")
if err != nil {
panic(err)
}
这里将 notify-keyspace-events
配置项的值设为 Ex
,表示只监听 key 的过期事件。如果还想监听其他事件类型,可以将值设为 Kx
, E
, g
, 或者它们的组合。
最后,在主线程中调用 client.Subscribe()
方法来订阅过期事件:
pubsub := client.Subscribe(context.Background(), "__keyevent@0__:expired")
defer pubsub.Close()
for {
msg, err := pubsub.ReceiveMessage(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Key %s expired\n", msg.Payload)
}
这里订阅了频道名为 "__keyevent@0__:expired"
的频道,该频道会在 Redis 中有任何一个 key 过期时触发。在循环中,使用 pubsub.ReceiveMessage()
方法来接收事件消息,并打印出过期的 key 的名称。
完整代码如下:
package main
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
err := client.ConfigSet(context.Background(), "notify-keyspace-events", "Ex")
if err != nil {
panic(err)
}
pubsub := client.Subscribe(context.Background(), "__keyevent@0__:expired")
defer pubsub.Close()
for {
msg, err := pubsub.ReceiveMessage(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Key %s expired\n", msg.Payload)
}
}