Redis 发布订阅模式及应用场景

Redis 发布订阅模式及应用场景


Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

1、常用的命令

命令描述
PUBLISH channel message将信息发送到指定的频道。
SUBSCRIBE channel [channel …]订阅给定的一个或多个频道的信息
PSUBSCRIBE pattern [pattern …]订阅一个或多个符合给定模式的频道。
UNSUBSCRIBE [channel [channel …]]指退订给定的频道。
PUNSUBSCRIBE [pattern [pattern …]]退订所有给定模式的频道。

2、实例演示

在这里插入图片描述
2.1 如下,客户机A订阅了news频道,客户机B也订阅了news频道;客户机C推送消息时,客户机A和客户机B都能收到消息。

(1)客户机C发送了消息 helloworld

[root@localhost redis-4.0.8]# redis-cli
127.0.0.1:6379> publish news helloworld!
(integer) 2
127.0.0.1:6379> 
[root@localhost redis-4.0.8]# 

(2)客户机A收到了消息

[root@localhost ~]# redis-cli
127.0.0.1:6379> subscribe news
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
1) "message"
2) "news"
3) "helloworld!"

(3)客户机B也收到了消息

[root@localhost redis-4.0.8]# redis-cli
127.0.0.1:6379> subscribe news
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
1) "message"
2) "news"
3) "helloworld!"

2.2 如下,客户机A订阅了news.*频道,客户机B也订阅了news.hello频道;客户机C推送消息到频道news.hello,客户机D推送消息到频道news.world;客户机A能收到客户机C和客户机D的消息,而客户机B只能收到客户机C的消息。
(1)客户机C分别向频道news.hello和news.world发送了消息

[root@localhost redis-4.0.8]# redis-cli
127.0.0.1:6379> public news.hello
127.0.0.1:6379> publish news.hello goodmorining
(integer) 2
127.0.0.1:6379> publish news.world nihao
(integer) 1
127.0.0.1:6379> 

(2)客户机A接收了消息

[root@localhost ~]# redis-cli
127.0.0.1:6379> psubscribe news.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "news.*"
3) (integer) 1
1) "pmessage"
2) "news.*"
3) "news.hello"
4) "goodmorining"
1) "pmessage"
2) "news.*"
3) "news.world"
4) "nihao"

(3)客户机B接收的消息

[root@localhost redis-4.0.8]# redis-cli
127.0.0.1:6379> subscribe news.hello
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news.hello"
3) (integer) 1
1) "message"
2) "news.hello"
3) "goodmorining"

3、常见应用场景

1、构建实时消息系统,比如普通的即时聊天,群聊等功能。

2、微信的公共号订阅消息推送等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值