redis事件机制

在上个星期之前一直不知道redis居然还有事件机制,一个研发同事问了下我,居然一直都不知道,但是BLPOP和RPUSH也算是事件啊。一直只是把它当做一个高速缓存和队列来使用。

具体的这个介绍可以参考: https://redis.io/topics/notifications  

在每个redis里可以设置3种事件,测试过把所有加上并不起作用,具体列表如下:

1
2
3
4
5
6
7
8
9
10
11
12
K     Keyspace events, published with __keyspace@<db>__ prefix.
E Keyevent events, published with __keyevent@<db>__ prefix.
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
$ String commands
l List commands
s Set commands
h Hash commands
z Sorted set commands
t Stream commands
x Expired events (events generated every time a key expires)
e Evicted events (events generated when a key is evicted for maxmemory)
A Alias for g$lshztxe, so that the "AKE" string means all the events.

设置的方式如下:

1
$ redis-cli config set notify-keyspace-events KEA 

接下来是如下看这个事件机制是否生效,在没看上面那篇文章的时候,我比较简单粗暴,直接使用ngrep来进行查看返回,ngrep是类似于tcpdump的一个网络dump工具,但是使用上更轻量。

1
2
sudo ngrep -d eth0 -q -Wbyline 22364505-b4f9-49c5-b5fd-1ab04a41fa78 port 6379 
T 10.10.10.96:6379 -> 10.10.100.100:42026 [AP] *4. $8. pmessage. $20. __keyevent@*:expired. $22. __keyevent@0__:expired. $42. 11831:22364505-b4f9-49c5-b5fd-1ab04a41fa78

当然更官方的做法是订阅事件就行了

1
2
3
4
5
6
7
8
$ redis-cli SUBSCRIBE 
__keyevent@0__:expired
1) "message"
2) "__keyevent@0__:expired"
3) "wtx:gtc:session:timer:5660:f0e468c3-238c-4872-854e-1f1f2cd4e525"
1) "message"
2) "__keyevent@0__:expired"
3) "5660:f0e468c3-238c-4872-854e-1f1f2cd4e525"

哈哈,官方的方法跟ngrep出来的结果还都差不多。