六. Redis发布订阅机制

发布订阅(pub/sub)是一种消息通信模式,主要是解除消息发布者和消息订阅者之间通信的耦合。

Redis作为一个pub/sub的服务器,在订阅者和发布者之间起到了一个消息路由的功能。订阅者可以通过subscribe和psubscribe命令向redis 服务器订阅自己感兴趣的消息类型,redis将信息类型称为通道(channel)。当发布者通过publish命令想redis server发送特定类型的信息时,订阅该信息类型的全部client都会收到此消息。

 

A客户端通过 SUBSCRIBE 订阅通道 TV1
127.0.0.1:6379> SUBSCRIBE TV1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "TV1"
3) (integer) 1
1) "message"
2) "TV1"
3) "hexu"

B客户端通过 SUBSCRIBE 订阅通道 TV1 TV2

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

 

发布者 通过 PUBLISH 命令 发布 TV1 的消息为 hexu,被 A客户端和B客户端接收到

127.0.0.1:6379> PUBLISH TV1 hexu
(integer) 2

 

 

通过C#端实现:

复制代码
 1 class PubOrSub
 2     {
 3         static void Main(string[] args)
 4         {
 5             using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("192.168.221.128:6379,password=hexu,allowAdmin=true"))
 6             {
 7                 redis.PreserveAsyncOrder = false;
 8 
 9                 Console.WriteLine("请输入Pub/Sub类型:");
10                 string type = Console.ReadLine();
11 
12                 if (type.Equals("Sub"))
13                 {
14                     Console.WriteLine("请输入订阅的频道:");
15                     string channel = Console.ReadLine();
16 
17                     var subscribe = redis.GetSubscriber();
18 
19                     subscribe.Subscribe(channel, (c, v) =>
20                     {
21                         Console.WriteLine(String.Format("{0}:{1}", c.ToString(), v.ToString()));
22                     });
23 
24                 }
25 
26 
27                 if (type.Equals("Pub"))
28                 {
29                     Console.WriteLine("请输入发布消息的频道名称:");
30                     string channel = Console.ReadLine();
31 
32                     Console.WriteLine("请输入发布的消息:");
33                     string message = Console.ReadLine();
34 
35                     var subscribe = redis.GetSubscriber();
36                     long x = subscribe.Publish(channel, message);
37 
38                 }
39                 Console.ReadKey();
40             }
41             
42         }
43     }
复制代码

 

posted on   何旭  阅读(1525)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示