初学Redis之PUB/SUB
程序员文章站
2022-04-27 23:52:25
...
转自https://blog.csdn.net/big2008bone/article/details/50344539
概述
在Redis中,你可以设定对某一个key值进行消息发布及消息订阅,当一个key值上进行了消息发布后,所有订阅它的客户端都会收到相应的消息。这一功能最明显的用法就是用作实时消息系统,比如普通的即时聊天,群聊等功能。
命令
实例
#A客户端链接redis数据库
[aaa@qq.com bin]# ./redis-cli -a daphne
127.0.0.1:6379>
#subscribe、publish
#A客户端订阅key auschat
127.0.0.1:6379> subscribe auschat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "auschat"
3) (integer) 1
打开另外客户端连接
#B客户端链接redis数据库
[aaa@qq.com bin]# ./redis-cli -a daphne
127.0.0.1:6379>
#B客户端按keyauschat发布消息
127.0.0.1:6379> publish auschat"asushiye is test publish"
#返回1 表示发布成功, 0 失败(可能A客户端没有订阅)
(integer) 1
#A客户端收到消息如下
127.0.0.1:6379> subscribe auschat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "auschat"
3) (integer) 1
#A客户端收到消息类型
1) "message"
#A客户端收到消息KEY
2) "auschat"
#A客户端收到消息内容
3) "asushiye is test publish"
#psubscribe、publish
#A客户端订阅key aus?chat 或key aus*chat 或 key aus[av]chat
127.0.0.1:6379> psubscribe aus?chat
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "aus?chat"
3) (integer) 1
127.0.0.1:6379> psubscribe aus*chat
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "aus*chat"
3) (integer) 1
127.0.0.1:6379> psubscribe aus[av]chat
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "aus[av]chat"
3) (integer) 1
#B客户端发布
#key aus?chat
127.0.0.1:6379> publish ausdchat"asushiye is test publish"
(integer) 1
127.0.0.1:6379> publish ausechat"asushiye is test publish"
(integer) 1
# key aus*chat
127.0.0.1:6379> publish ausechat"asushiye is test publish"
(integer) 1
127.0.0.1:6379> publish auseasdfchat"asushiye is test publish"
(integer) 1
# key aus[av]chat
127.0.0.1:6379> publish ausachat"asushiye a is test publish"
(integer) 1
127.0.0.1:6379> publish ausechat"asushiye a is test publish"
(integer) 0
127.0.0.1:6379> publish ausvchat"asushiye a is test publish"
(integer) 1
#unsubscribe、punsubscribe
#从给定的信道退订客户端
127.0.0.1:6379> unsubscribe aus[ab]chat
1) "unsubscribe"
2) "aus[ab]chat"
3) (integer) 0
#从给定的模式信道退订客户端
127.0.0.1:6379> punsubscribe aus?chat
1) "punsubscribe"
2) "aus?chat"
3) (integer) 0
#pubsub
#A客户端订阅key auschat
127.0.0.1:6379> subscribe auschat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "auschat"
3) (integer) 1
#C客户端
127.0.0.1:6379> pubsub channels
1) "auschat"
127.0.0.1:6379> pubsub numsub auschat
1) "auschat"
2) (integer) 1
#A客户端订阅key aus?chat
127.0.0.1:6379> psubscribe aus?chat
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "aus?chat"
3) (integer) 1
#C客户端
127.0.0.1:6379> pubsub numpat
(integer) 1
命令
型
时间
命令描述
下一篇: Java端口监听的实现代码