9. Redis 发布订阅模式

Redis 发布订阅模式

原文:https://ooyhao.github.io/categories/DB/Redis/

简介

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

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

下图展示了频道channel 1 , 以及订阅这个频道的三个客户端 – client2, client5, client1之间的关系:

在这里插入图片描述

当有新消息通过publish命令发送到频道channel1时,这个消息就会被发送给订阅它的三个客户端:

在这里插入图片描述

实例

下面我们通过实验来实现以下:

  1. 首先打开两个窗口,用来模拟两个客户端,并且同时订阅channel1频道。
  2. 再打开一个窗口,用来模拟发布者发送消息。

发布者截图:

在这里插入图片描述

订阅者截图:

在这里插入图片描述

在这里插入图片描述

命令集合

publish

PUBLISH channel message

publish 命令用于将信息发布到指定的频道中去。

127.0.0.1:6379> publish c2 "hello redis!"
(integer) 1
subscribe

SUBSCRIBE channel [channel ...]

subscribe 命令用于订阅给定的一个或多个频道的信息。

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
psubscribe

PSUBSCRIBE pattern [pattern ...]

psubscribe 命令订阅一个或多个符合给定模式的频道。每个模式以 * 作为通配符,比如 it* 匹配所有以it开头的频道(itenews, it.news, it.blog, it.tweets等等)。news.* 匹配所有以new.开头的频道(news.it, news.global.today等等)。

发布端:

127.0.0.1:6379> publish news.it "message news it"
(integer) 1

订阅端:

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.it"
4) "message news it"

可以看出,使用psubscribe 可以按模式规则进行订阅。

unsubscribe

UNSUBSCRIBE [channel [channel ...]]

unsubscribe 命令用于退订给定的一个或多个频道的信息。

punsubscribe

PUNSUBSCRIBE [pattern [pattern ...]]

punsubscribe 命令用于退订所有给定模式的频道。

注意:

redis中的发布订阅系统在某些场景下还是非常好用的,但是也有一些问题需要注意:由于网络在传输过程中可能会遭遇到断线等意外情况,断线后需要重新连接,然而这会导致断线期间的数据丢失。

好了,Redis的发布订阅模式就到这里了。更加详细的文档请移步官网。

redis官网:http://www.redis.cn/commands.html#pubsub

参考自:

https://www.runoob.com/redis/redis-pub-sub.html

http://www.javaboy.org/2019/0615/redis-pub-sub.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值