Redis发布、订阅

Redis发布订阅

发布订阅模式中发布消息的为publisher即发布者,接收消息的为subscriber即订阅者。在Redis中,所有的消息通过channel即频道进行发布,一个发布者可以向多个channel发布消息,一个订阅者也可以订阅多个channel。Redis不对消息进行持久化,如果消息发布时订阅者还没有进行订阅,则不会再收到此消息。

 

发布订阅命令

命令格式说明
PUBLISHPUBLISH channel message发布message到指定的channel
SUBSCRIBESUBSCRIBE channel [channel ...]订阅1个或多个指定的channel
UNSUBSCRIBEUNSUBSCRIBE [channel [channel ...]]取消订阅1个或多个指定的channel,如果不指定channel退订所有通过SUBSCRIBE订阅的channel
PSUBSCRIBEPSUBSCRIBE pattern [pattern ...]根据匹配模式订阅channel
PUNSUBSCRIBEPUNSUBSCRIBE [pattern [pattern ...]]根据匹配模式取消订阅channel,如果不指定匹配模式退订所有通过PSUBSCRIBE订阅的channel

 

subscribe不能重复订阅同一个channel,而psubscribe按照匹配模式订阅时有可能会多次订阅同一个channel。如果psubscribe多次订阅了同一个channel,发布者使用publish发布消息到此channel后,订阅者会多次收到此消息。

unsubscribe只能退订subscribe订阅的channel,punsubscribe只能退订psubscribe订阅的channel。



订阅方法

       // <summary>
        /// 订阅
        /// </summary>
        public static void Subscription()
        {
            using (ServiceStack.Redis.RedisClient consumer = new RedisClient("192.168.210.36", 6379))
            {
                //创建订阅
                ServiceStack.Redis.IRedisSubscription subscription = consumer.CreateSubscription();

                //接收消息处理Action
                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("订阅客户端:开始订阅" + channel);
                };

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

                //订阅频道
                subscription.SubscribeToChannels("channel-1");
            }

        }
发布程序

static void Main(string[] args)
        {
            Console.Title = "Redis发布、订阅服务";

            RedisClient client = new RedisClient("192.168.210.36", 6379);
            while (true)
            {
                string input = Console.ReadLine();
                client.PublishMessage("channel-1", input);
            }
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值