【Redis】Redis 发布订阅通信模式 ( 发布订阅模式

您所在的位置:网站首页 redis登录命令 【Redis】Redis 发布订阅通信模式 ( 发布订阅模式

【Redis】Redis 发布订阅通信模式 ( 发布订阅模式

2023-04-01 10:52| 来源: 网络整理| 查看: 265

文章目录

一、发布订阅模式二、订阅频道三、发布消息四、接收消息一、发布订阅模式

Redis 中 存在一种 发布订阅 消息通信模式 :

消息发布者 : 负责发送消息 , 订阅者需要订阅该发布者频道 ;消息订阅者 : 负责接收消息 ;

订阅者 先 订阅 发布者频道 , 当 发布者 发布消息时 , 订阅者 会接收到该信息 ;

在 Redis 中 , 发布者 是 消息频道 , 订阅者 是 Redis 客户端 ;

一个 Redis 客户端可以 订阅多个 消息频道 ;一个 消息频道 可以 被多个 Redis 客户端 订阅 ;

当 消息频道 发送消息后 , 订阅该频道的 客户端 , 就会收到该频道发送的消息 ;

二、订阅频道

订阅频道 : 在一个命令行中 , 执行

subscribe channel1

命令 , 可以 订阅 名称为 channel1 的 消息频道 ;

上述命令执行后 , 在命令行中会 阻塞等待 channel1 的消息到来 ;

代码示例 :

127.0.0.1:6379> subscribe channel1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel1" 3) (integer) 1三、发布消息

重新打开一个 CMD 命令行工具 , 执行

publish channel1 hello

命令 , 向 channel1 通道中 , 发送 hello 消息 ;

代码示例 :

127.0.0.1:6379> publish channel1 hello (integer) 1 127.0.0.1:6379>四、接收消息

命令行 1 中 , 执行 subscribe channel1 命令 , 订阅了 channel1 频道 ;

命令行 2 中 , 执行 publish channel1 hello 命令 , 向 channel1 频道发送了 hello 消息 ;

然后在 命令行 1 中 , 接收到了 hello 消息 ;

代码示例 :

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

接收的消息内容是 :

1) "message" 2) "channel1" 3) "hello"


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3