天天看点

Redis教程09(发布和订阅)

之前几篇文章给大家介绍了redis的五种数据类型及相关的命令,本文介绍redis中比较简单的发布订阅

Redis发布和订阅

Redis 发布订阅(pub/sub)是一种消息通信模式:

发送者(pub)发送消息

订阅者(sub)接收消息

Redis 客户端可以订阅任意数量的频道

订阅消息

客户端订阅消息的命令如下

127.0.0.1:6379> subscribe c1 c2 c3
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
1) "subscribe"
2) "c2"
3) (integer) 2
1) "subscribe"
2) "c3"
3) (integer) 3      

发送消息如下命令:

127.0.0.1:6379> publish c1 "hello redis"
(integer) 1
127.0.0.1:6379> publish c2 'hehe'
(integer) 1      

客户端同时会接收到消息:

127.0.0.1:6379> subscribe c1 c2 c3
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
1) "subscribe"
2) "c2"
3) (integer) 2
1) "subscribe"
2) "c3"
3) (integer) 3
1) "message"
2) "c1"
3) "hello redis" #接收到c1发送的消息
1) "message"
2) "c2" 
3) "hehe" #接收到c2发送的消息      

模式订阅消息

客户端在订阅消息的时候还可以通过模式匹配订阅的方式订阅,如下

127.0.0.1:6379> psubscribe c*
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c*" #订阅所有发送则是c开头的消息
3) (integer) 1      

发送消息,没有区别

127.0.0.1:6379> publish c1 "hello redis"
(integer) 1      

接收消息

127.0.0.1:6379> psubscribe c*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "c*"
3) (integer) 1
1) "pmessage"
2) "c*"
3) "c1"
4) "hello redis" #自动接收到c1发送来的消息      

发布订阅要注意网络连接断开的话需要重新连接,此时就会有可能数据的丢失。这个需要注意~

继续阅读