redis发布订阅(pub/sub)是一种消息通信模式:发布者(pub)发布消息,订阅者(sub)接收消息。
redis客户端可以订阅任意数量的频道。
2、redis的发布和订阅 2.1、客户端可以订阅频道如下图 2.2、当给这个频道发布消息后,消息就会发送给订阅的客户端 3、发布和订阅的命令行实现 3.1、打开一个客户端订阅channel13.2、打开另一个客户端,给channel1发布消息hello订阅命令: subscribe channel1 channel2 ... ,可以订阅多个频道。
3.3、切换到订阅者窗口,可以看到收到信息了 4、发布和订阅常用命令 4.1、subscribe:订阅一个或者多个频道发标消息命令: publish channel 消息 ,返回值表示有几个订阅者
SUBSCRIBE channel [channel ...]
订阅给定的一个或多个频道的信息。
返回值:接收到的信息(请参见下面的代码说明)。
# 订阅 msg 和 chat_room 两个频道 # 1 - 6 行是执行 subscribe 之后的反馈信息 # 第 7 - 9 行才是接收到的第一条信息 # 第 10 - 12 行是第二条 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"4.2、publish:发布消息到指定的频道
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) 34.3、psubscribe:订阅一个或多个符合给定模式的频道
PSUBSCRIBE pattern [pattern ...]
订阅一个或多个符合给定模式的频道。
每个模式以 * 作为匹配符,比如 it* 匹配所有以 it 开头的频道( it.news 、 it.blog 、it.tweets 等等), news.* 匹配所有以 news. 开头的频道( news.it 、 news.global.today 等等),诸如此类。
# 订阅 news.* 和 tweet.* 两个模式 # 第 1 - 6 行是执行 psubscribe 之后的反馈信息 # 第 7 - 10 才是接收到的第一条信息 # 第 11 - 14 是第二条 # 以此类推。。。 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"



