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 
  • 相关阅读:
    recommend a wait button on web page
    ref: 这正是BI工具的精髓:它不是让你相信自己所知道的,而是促使你去思考更多的问题和疑惑。
    asp.net 中使用iframe动态加载页面
    forbid cache page in asp.net
    转贴: 想使你的公司有所创新吗?
    treeview 的使用心得
    ref: 九大数据仓库方案特点比较
    recommend a cool calendar
    Servlet与Jsp学习笔记10、Localized
    重复表的操作
  • 原文地址:https://www.cnblogs.com/h--d/p/11466589.html
Copyright © 2011-2022 走看看