Redis 系列六之发布订阅

   #region ---发布/订阅---

        /// 
        /// 发布
        /// 
        /// 频道
        /// 消息
        public void Publish(string toChannel, string message)
        {
            try
            {
                using (IRedisClient redisClient = GetClient())
                {
                    redisClient.PublishMessage(toChannel, message);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// 
        /// 订阅
        /// 
        /// 频道
        public void Psubscribe(string toChannel)
        {
            try
            {
                using (IRedisClient redisClient = GetClient())
                {
                    //创建订阅
                    IRedisSubscription sub = redisClient.CreateSubscription();
                    //订阅频道
                    sub.SubscribeToChannels(new string[] { toChannel });
                    //订阅频道时
                    sub.OnSubscribe = (channel) =>
                    {
                        Console.WriteLine("订阅客户端:开始订阅" + channel);
                    };
                    //接受到消息时
                    sub.OnMessage = (channel, msg) =>
                    {
                        Console.WriteLine(string.Format("从频道:{0}上接受到消息:{1},时间:{2}"), channel, msg, DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                        Console.WriteLine(string.Format("频道订阅数目:{0}", sub.SubscriptionCount));
                        Console.WriteLine("___________________________________________________________________");
                    };
                    //取消订阅频道时
                    //sub.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端:取消订阅"); };
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

 

你可能感兴趣的:(Redis)