六. 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 @ 2016-02-03 13:41  何旭  阅读(1516)  评论(0编辑  收藏  举报