ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 go 服务监听过期的 key <details> <summary>main.go</summary> ``` package main import ( //"github.com/go-redis/redis" "fmt" "github.com/prometheus/common/log" "time" "unsafe" "github.com/gomodule/redigo/redis" ) type PSubscribeCallback func(pattern, channel, message string) type PSubscriber struct { client redis.PubSubConn cbMap map[string]PSubscribeCallback } func (c *PSubscriber) PConnect(ip string, port uint16) { conn, err := redis.Dial("tcp", "127.0.0.1:6379") if err != nil { panic("redis dial failed.") } c.client = redis.PubSubConn{conn} c.cbMap = make(map[string]PSubscribeCallback) go func() { for { log.Debug("wait...") switch res := c.client.Receive().(type) { case redis.Message: fmt.Printf("%+v\n", res.Pattern) pattern := (*string)(unsafe.Pointer(&res.Pattern)) channel := (*string)(unsafe.Pointer(&res.Channel)) message := (*string)(unsafe.Pointer(&res.Data)) c.cbMap[*channel](*pattern, *channel, *message) case redis.Subscription: fmt.Printf("%s: %s %d\n", res.Channel, res.Kind, res.Count) case error: log.Error("error handle...") continue } } }() } func (c *PSubscriber) Psubscribe(channel interface{}, cb PSubscribeCallback) { err := c.client.PSubscribe(channel) if err != nil { panic("redis Subscribe error.") } c.cbMap[channel.(string)] = cb } func TestPubCallback(patter, chann, msg string) { log.Debug("TestPubCallback patter : "+patter+" channel : ", chann, " message : ", msg) } func main() { log.Info("===========main start============") var psub PSubscriber psub.PConnect("127.0.0.1", 6397) psub.Psubscribe("__keyevent@0__:expired", TestPubCallback) for { time.Sleep(1 * time.Second) } } ``` </details> <br /> 配置 redis.conf ``` notify-keyspace-events KEA ``` 运行redis server ``` > /usr/local/bin/redis-server redis.conf ``` 运行 redis-cli ``` 127.0.0.1:6379> set runooobkey h1 127.0.0.1:6379> EXPIRE runooobkey 1 ```