• redis(3)发布订阅


    一、发布/订阅模式

    在软件工程里面,发布/订阅是一种消息模式,这种模式旨在将消息发送者和消息接收者解耦。发送者不需要关心将消息发送给谁,接收者也不需要知道消息的发送者是谁。发送者将消息发布以后就结束动作,接收者可以订阅自己感兴趣的消息。

    除了发布/订阅模式还有一种和它很类似的,消息队列,是一种典型的面向消息中间件的系统。许多消息系统都会同时支持发布/订阅和消息队列模型,例如Java Message Service(JMS)

    参见:维基百科

    二、redis的发布/订阅

    我们从一个简单的示例开始,首先我们启动redis-server服务端,然后打开两个redis-cli客户端,我们将两个客户端分别称作client1、client2

    1)client1 使用 subscribe 命令订阅了频道 channel:chat

    127.0.0.1:6379> subscribe channel:chat
    Reading messages... (press Ctrl-C to quit)
    1) "subscribe"
    2) "channel:chat"
    3) (integer) 1

    2)client2 向频道channel:chat发布了一个消息

    127.0.0.1:6379> publish channel:chat "hey client1"
    (integer) 1

    3)我们看到client1接收到的消息如下:

    127.0.0.1:6379> subscribe channel:chat
    Reading messages... (press Ctrl-C to quit)
    1) "subscribe"
    2) "channel:chat"
    3) (integer) 1
    1) "message"
    2) "channel:chat"
    3) "hey client1"

    message 表示 消息类型是消息发布的接收,频道是channel:chat,消息主体是:hey client1

    以上,我们通过redis简单实现了一个发布订阅操作。

    三、消息的格式

    一个发布/订阅消息是一个数组,包括三个元素。

    第一个元素是消息的类型:

    1)subscribe: 表示订阅成功类型

    2) unsubscribe: 表示退订成功类型

    3) message: 表示接收到发布的消息

    第二个元素表示的是当前订阅或者退订的频道

    第三个元素表示当前订阅的频道数量或者是消息体

    四、订阅多个频道

    redis的发布/订阅支持订阅多个频道,如:

    subscribe channel:first channel:second

    当接收到对应频道的消息时,按照消息格式接收消息

    五、匹配订阅频道

    redis中支持通过通配符来订阅频道,需要用到命令:psubscribe,如:

    client1订阅了channel:*通配符表示的多个频道

    127.0.0.1:6379> psubscribe channel:*
    Reading messages... (press Ctrl-C to quit)
    1) "psubscribe"
    2) "channel:*"
    3) (integer) 1

    client2分别在channel:1和channel:2两个频道发布了消息

    127.0.0.1:6379> publish channel:chat "hey client1"
    (integer) 1
    127.0.0.1:6379> publish channel:1 "hey this is channel1"
    (integer) 1
    127.0.0.1:6379> publish channel:2 "hey this is channel2"
    (integer) 1

    我们看到client1接收到了两个频道的消息

    127.0.0.1:6379> psubscribe channel:*
    Reading messages... (press Ctrl-C to quit)
    1) "psubscribe"
    2) "channel:*"
    3) (integer) 1
    1) "pmessage"
    2) "channel:*"
    3) "channel:1"
    4) "hey this is channel1"
    1) "pmessage"
    2) "channel:*"
    3) "channel:2"
    4) "hey this is channel2"

    六、发布订阅的命令

    psubscribe: 订阅

    publish: 发布

    pubsub: 检查

    punsubscribe: 取消订阅

    subscribe: 订阅

    unsubscribe: 取消订阅

    具体使用参考:redis官网

  • 相关阅读:
    C++——STL内存清除
    c++——智能指针学习(unique_ptr)
    linux下将tomcat加入服务
    linux下oracle远程连接的问题
    oracle计算容量的方式
    oracle删除表的方式
    阻塞与非阻塞的区别
    java中queue的使用
    yum源
    VMware Tools 安装
  • 原文地址:https://www.cnblogs.com/lay2017/p/9256378.html
Copyright © 2020-2023  润新知