Redis专题之3、第3篇:Redis的发布和订阅

3.1、什么是发布和订阅

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

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

3.2、redis的发布和订阅

1、客户端可以订阅频道如下图

2、当给这个频道发布消息后,消息就会发送给订阅的客户端

3.3、发布和订阅的命令行实现

1、打开一个客户端订阅channel1

订阅命令:subscribe channel1 channel2 ...,可以订阅多个频道。

2、打开另一个客户端,给channel1发布消息hello

发标消息命令:publish channel 消息,返回值表示有几个订阅者

3、切换到订阅者窗口,可以看到收到信息了

3.4、发布和订阅常用命令

3.4.1、subscribe:订阅一个或者多个频道

  1. SUBSCRIBE channel [channel ...]

订阅给定的一个或多个频道的信息。

返回值:接收到的信息(请参见下面的代码说明)。



redis> subscribe msg chat_room
Reading messages... (press Ctrl-C to quit)
1) "subscribe"       # 返回值的类型:显示订阅成功
2) "msg"             # 订阅的频道名字
3) (integer) 1       # 目前已订阅的频道数量

1) "subscribe"
2) "chat_room"
3) (integer) 2

1) "message"         # 返回值的类型:信息
2) "msg"             # 来源(从那个频道发送过来)
3) "hello moto"      # 信息内容

1) "message"
2) "chat_room"
3) "testing...haha"

3.4.2、publish:发布消息到指定的频道

  1. PUBLISH channel message

将信息 message 发送到指定的频道 channel

返回值:接收到信息 message 的订阅者数量。

redis> publish bad_channel "can any body hear me?"
(integer) 0

redis> publish msg "good morning"
(integer) 1

redis> publish chat_room "hello~ everyone"
(integer) 3

3.4.2、psubscribe:订阅一个或多个符合给定模式的频道

  1. PSUBSCRIBE pattern [pattern ...]

订阅一个或多个符合给定模式的频道。

每个模式以 * 作为匹配符,比如 it* 匹配所有以 it 开头的频道( it.newsit.blogit.tweets 等等), news.* 匹配所有以 news. 开头的频道( news.itnews.global.today 等等),诸如此类。



redis> psubscribe news.* tweet.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"                  # 返回值的类型:显示订阅成功
2) "news.*"                      # 订阅的模式
3) (integer) 1                   # 目前已订阅的模式的数量

1) "psubscribe"
2) "tweet.*"
3) (integer) 2

1) "pmessage"                    # 返回值的类型:信息
2) "news.*"                      # 信息匹配的模式
3) "news.it"                     # 信息本身的目标频道
4) "Google buy Motorola"         # 信息的内容

1) "pmessage"
2) "tweet.*"
3) "tweet.huangz"
4) "hello"

1) "pmessage"
2) "tweet.*"
3) "tweet.joe"
4) "@huangz morning"

1) "pmessage"
2) "news.*"
3) "news.life"
4) "An apple a day, keep doctors away"
来源:http://www.itsoku.com/course/15/250
posted @ 2022-04-27 10:52  程序员小明1024  阅读(204)  评论(0编辑  收藏  举报