發佈訂閱(pub/sub)是一種消息通訊模式,主要是解除消息發佈者和消息訂閱者之間通訊的耦合。redis
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"ui
B客戶端經過 SUBSCRIBE 訂閱通道 TV1 TV2spa
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) 2code
發佈者 經過 PUBLISH 命令 發佈 TV1 的消息爲 hexu,被 A客戶端和B客戶端接收到orm
127.0.0.1:6379> PUBLISH TV1 hexu
(integer) 2server
經過C#端實現:blog
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 }