监听过期 key
最后更新于:2022-04-02 04:00:43
[TOC]
## 概述
go 服务监听过期的 key
配置 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 ```
';
main.go
``` 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) } } ```配置 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 ```