9.Redis 发布订阅模式

Redis 发布订阅模式

简介

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

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

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

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

实例

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

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

发布者截图:

订阅者截图:

命令集合

publish

PUBLISH channel message

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

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

subscribe

SUBSCRIBE channel [channel ...]

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

1
2
3
4
5
6
7
8
9
10
11
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等等)。

发布端:

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

订阅端:

1
2
3
4
5
6
7
8
9
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

#

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×