【Redis】Redis 发布订阅

Redis 发布订阅介绍

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

  Redis 客户端能够订阅任意数量的频道。ui

  下图展现了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:spa

    

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

    

实例

  如下实例演示了发布订阅是如何工做的。在实例中建立了订阅频道名为 redisChat:blog

1 127.0.0.1:6379> SUBSCRIBE redisChat
2 Reading messages... (press Ctrl-C to quit)
3 1) "subscribe"
4 2) "redisChat"
5 3) (integer) 1

  如今,先从新开启个 redis 客户端,而后在同一个频道 redisChat 发布两次消息,订阅者就能接收到消息。it

1 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"
2 (integer) 1
3 127.0.0.1:6379> PUBLISH redisChat "Learn redis by runoob.com"
4 (integer) 1
1 # 订阅者的客户端会显示以下消息
2 1) "message"
3 2) "redisChat"
4 3) "Redis is a great caching technique"
5 1) "message"
6 2) "redisChat"
7 3) "Learn redis by runoob.com"

Redis 发布订阅命令

  一、Redis Psubscribe 命令订阅一个或多个符合给定模式的频道。class

    每一个模式以 * 做为匹配符,好比 it* 匹配全部以 it 开头的频道( it.news 、 it.blog 、 it.tweets 等等)。 news.* 匹配全部以 news. 开头的频道( news.it 、 news.global.today 等等),诸如此类。cli

    语法:PSUBSCRIBE pattern [pattern ...]语法

1 127.0.0.1:6379> PSUBSCRIBE mychannel
2 Reading messages... (press Ctrl-C to quit)
3 1) "psubscribe"
4 2) "mychannel"
5 3) (integer) 1

  二、Redis Pubsub 命令用于查看订阅与发布系统状态,它由数个不一样格式的子命令组成。channel

    语法:PUBSUB <subcommand> [argument [argument ...]]

1 127.0.0.1:6379> PUBSUB CHANNELS
2 (empty list or set)

  三、Redis Publish 命令用于将信息发送到指定的频道。

    语法:PUBLISH channel message

1 127.0.0.1:6379> PUBLISH mychannel "hello, i m here"
2 (integer) 1

  四、Redis Punsubscribe 命令用于退订全部给定模式的频道。

    语法:PUNSUBSCRIBE [pattern [pattern ...]]

1 127.0.0.1:6379> PUNSUBSCRIBE mychannel 
2 1) "punsubscribe"
3 2) "mychannel"
4 3) (integer) 0

  五、Redis Subscribe 命令用于订阅给定的一个或多个频道的信息。

    语法:SUBSCRIBE channel [channel ...]

1 127.0.0.1:6379> SUBSCRIBE mychannel 
2 Reading messages... (press Ctrl-C to quit)
3 1) "subscribe"
4 2) "mychannel"
5 3) (integer) 1

   六、Redis Unsubscribe 命令用于退订给定的一个或多个频道的信息。

    语法:UNSUBSCRIBE channel [channel ...]

1 127.0.0.1:6379> UNSUBSCRIBE mychannel 
2 1) "unsubscribe"
3 2) "mychannel"
4 3) (integer) 0 
相关文章
相关标签/搜索