Redis的订阅发布

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using ServiceStack.Common;
using System.Threading;
namespace RedisTest2
{
    class Program
    {
       
        static void Main(string[] args)
        {
        
        
            Console.WriteLine("请输入发布订阅类型?");
            var type = Console.ReadLine();
            if (type == "pub")
            {
                Pub();
            }
            else
            {
                Sub();
            }
        }


        public static void Pub()
        {
            using (IRedisClient publisher = new RedisClient("127.0.0.1", 6379))
            {
               
                while (true)
                {
                    var msg = Console.ReadKey();
                    publisher.PublishMessage("c1", string.Format("这是我发送的第消息!{0}", DateTime.Now));
                }
             
            }

            //using (IRedisClient publisher = new RedisClient("127.0.0.1", 6379))
            //{
            //    //for (int i = 1; i <= 100; i++)
            //    //{
            //    while (true)
            //    {
                   
            //        publisher.PublishMessage("c1", string.Format("这是我发送的第消息!{0}", DateTime.Now));
            //    }
            //       // Thread.Sleep(200);
            //   // }
            //}
        }


        /// <summary>
        /// 订阅
        /// 一个客户端订阅c1
        /// </summary>
        public static void Sub()
        {
            using (var consumer = new RedisClient("127.0.0.1", 6379))
            {
                //创建订阅
                IRedisSubscription subscription = consumer.CreateSubscription();

                //接受到消息时的委托
                subscription.OnMessage = (channel, msg) =>
                {
                    Console.WriteLine("频道【" + channel + "】订阅客户端接收消息:" + ":" + msg + " [" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]");
                    Console.WriteLine("订阅数:" + subscription.SubscriptionCount);
                    Console.WriteLine("___________________________________________________________________");
                };

                //订阅事件处理
                subscription.OnSubscribe = channel => { Console.WriteLine("订阅客户端a:开始订阅" + channel); };

                //取消订阅事件处理
                subscription.OnUnSubscribe = a => { Console.WriteLine("订阅客户端:取消订阅"); };

                //订阅频道
                subscription.SubscribeToChannels("c1");

            }
        }

    
    }
}
View Code

 参考 http://blog.csdn.net/wulex/article/details/52712664

posted @ 2017-03-23 14:12  甜菜波波  阅读(140)  评论(0编辑  收藏  举报