redis的发布订阅模式

redis的发布订阅模式

redis发布订阅(pub/sub)是一种消息通信模式 ,消息的发布者不会将消息发送给特定的订阅者,而是通过消息通道(频道)广播出去,让订阅该消息主题(频道)的订阅者消费。发布/订阅模式的最大特点是利用消息中间件,实现松耦合

使用场景

稍微复杂的场景就需要专业的消息中间件了如RabbitMQ,kafka

  • 实时消息系统
  • 实时聊天

发布订阅的使用与实现原理

redis的发布订阅又分为两类:

  • 频道的发布订阅
  • 模式的发布订阅

频道的发布订阅

1.使用

使用subscribe命令指定当前客户端订阅的频道,一个订阅者可以订阅多个频道,若该频道不存在则会创建

subscribe channel channel2 : 订阅一个或多个频道

127.0.0.1:6379> subscribe shen-channel1 shen-channel2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"      --返回值类型:订阅者
2) "shen-channel1"  --订阅频道名称
3) (integer) 1      --当前客户端已订阅频道的梳理
1) "subscribe"
2) "shen-channel2"
3) (integer) 2

使用publish命令指定当前客户端向某个频道发布消息

publish channel message : 向channel频道发送message消息

127.0.0.1:6379> publish shen-channel1 11
(integer) 1       --接收到此消息的订阅者数量,无订阅者返回0
127.0.0.1:6379> publish shen-channel2 11
(integer) 1

当发布者发送消息后,订阅者会接收到消息

1) "message"         --返回值类型:消息
2) "shen-channel1"   --接收的频道名
3) "11"              --消息内容
1) "message"
2) "shen-channel2"
3) "11"

使用pubsub命令可以查看频道的基本信息

pubsub channels : 查看当前存在的所有频道
pubsub numsub  channel : 查看指定频道的订阅者数量

使用unsubscribe命令可以指定当前客户端退订1个或多个频道

unsubscribe channel1 channel2 :退订频道

127.0.0.1:6379> unsubscribe shen-channel
1) "unsubscribe"    --返回类型:退订
2) "shen-channel"   --退订的频道名
3) (integer) 1 

2.实现原理

在redisServer中有一个字典类型字段叫pubsub_channels,用来保存订阅信息,key为频道,value为订阅该频道的客户端

struct redisServer{
    pid_t pid;
    //...
    // 保存所有频道订阅关系
    dict *pubsub_channels;
    //...
}

模式的发布订阅

在基于频道的订阅中,我们输入频道的完整名称实现订阅,而在模式的订阅则不需要指定全名,用模糊匹配多个字符串,通配符中?表示1个占位符,*表示任意任意个占位符,eg: shen. * 相当于订阅了shen.xx的频道

1.使用

使用psubscribe命令进行模式订阅

psubscribe pattern-1 pattern-2 :订阅1个或多个模式频道

127.0.0.1:6379> psubscribe shen-* test?
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"   --返回类型:模式订阅
2) "shen-*"       --订阅模式名称  shen-xxx
3) (integer) 1    --目前已订阅的数量
1) "psubscribe"
2) "test?"        --订阅模式名称  testx
3) (integer) 2

仍然使用publish命令指定当前客户端向某个频道发布消息

127.0.0.1:6379> publish shen-channel 1
(integer) 1
127.0.0.1:6379> publish test1 1
(integer) 1

当发布者发送消息后,订阅者会接收到消息

1) "pmessage"
2) "shen-*"
3) "shen-channel"
4) "1"
1) "pmessage"
2) "test?"
3) "test1"
4) "1"

使用punsubscribe命令可以指定当前客户端退订1个或多个模式

punsubscribe pattern-1 pattern-2 : 退订1个或多个模式频道

127.0.0.1:6379> punsubscribe shen-* test?
1) "punsubscribe"
2) "shen-*"
3) (integer) 0

4.实现原理

在redisServer中有一个链表字段叫pubsub_patterns,该链表保存者所有和模式相关的信息

struct redisServer {
    //...
    list *pubsub_patterns; 
    // ...
}

typedef struct pubsubPattern {
    client *client;  -- 订阅模式客户端
    robj *pattern;   -- 被订阅的模式
} pubsubPattern;

参考网址

https://blog.csdn.net/wzngzaixiaomantou/article/details/125690765

https://zhuanlan.zhihu.com/p/432572553

posted @ 2022-10-16 18:33  柯南。道尔  阅读(1029)  评论(0编辑  收藏  举报