从例子看redis notification

https://redis.io/topics/notifications

背景:
1)默认是不开启的,可以通过conf文件开启,也可以在客户端配置:

redis-cli config set notify-keyspace-events KEA

开启的参数KEA是三个参数的组合,表示所有能通知的都通知。这是所有参数官网的解释:

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
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$lshzxe, so that the "AKE" string means all the events.

要关闭传空字符串作为参数:

redis-cli config set notify-keyspace-events ''

2)通知有两种方式space和event,区别是对于space:是key/operation;另一个event是operation/key:

PUBLISH keyspace@0:mykey del
PUBLISH keyevent@0:del mykey
对expired事件通知是准实时的:1)如果客户端访问某个key时 2)redis自己的background运行的垃圾收集它会轮流访问有ttl的key,此时相当于第一条。

3)因为是pubsub机制,可以有多个客户端同时得到通知。并且pubsub不提供可靠交付(暂时),意味着如果客户端重启这段时间的通知会丢。

4)set相同key不管值是否相同都会通知,del 如果key存在会通知,否则不通知;

例子
客户端A:

127.0.0.1:6379[1]> set foo 2
OK
127.0.0.1:6379[1]> del foo 2
(integer) 1

客户端B:

# redis-cli
127.0.0.1:6379> psubscribe '__key*__:*'
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "__key*__:*"
3) (integer) 1
1) "pmessage"
2) "__key*__:*"
3) "__keyspace@1__:foo"
4) "set"
1) "pmessage"
2) "__key*__:*"
3) "__keyevent@1__:set"
4) "foo"
1) "pmessage"
2) "__key*__:*"
3) "__keyspace@1__:foo"
4) "del"
1) "pmessage"
2) "__key*__:*"
3) "__keyevent@1__:del"
4) "foo"

如果只对设置了ttl的key的expired感兴趣:

127.0.0.1:6379> psubscribe '__key*__:expired'

如果只对event感兴趣:

127.0.0.1:6379> psubscribe '__keyevent@1__:expired'
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页