zoukankan      html  css  js  c++  java
  • 【Redis】Redis 发布订阅

    Redis 发布订阅介绍

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

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

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

        

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

        

    实例

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

    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 发布两次消息,订阅者就能接收到消息。

    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 发布订阅命令

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

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

        语法: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

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

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

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

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

        语法:PUBLISH channel message

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

      4、Redis Punsubscribe 命令用于退订所有给定模式的频道。

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

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

      5、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

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

        语法:UNSUBSCRIBE channel [channel ...]

    1 127.0.0.1:6379> UNSUBSCRIBE mychannel 
    2 1) "unsubscribe"
    3 2) "mychannel"
    4 3) (integer) 0 
  • 相关阅读:
    Linux下判断字符串长度
    Linux下使用xargs得到字符串作为参数进行输出、awk得到字符串作为参数进行输出
    Linux下使用xargs将多行文本转换成一行并用tr实现逗号隔开
    Linux下使用split按行数进行切割
    Maven设置snapshot无法在远程仓库下载的问题解决
    Intellij IDEA自动生成serialVersionUID
    Spring中@Value用法收集
    Http报头Accept与Content-Type的区别(转)
    Linux下Shell的for循环语句
    Shell脚本中的分号使用
  • 原文地址:https://www.cnblogs.com/h--d/p/11466589.html
Copyright © 2011-2022 走看看