如何使用Servicestack.Redis中的“New Managed Pub / Sub Server”取消订阅频道

时间:2015-09-25 07:34:33

标签: c# redis servicestack servicestack.redis

New Managed Pub/Sub Server文档中,他们展示了如何在pubsubserver的初始化中订阅频道。但是,如果需要,您如何在程序后期取消订阅特定频道?

我的代码:

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace va.communication
{
    class Program
    {
        static void Main(string[] args)
        {
            var clientsManager = new PooledRedisClientManager();

            //subscribe to channels 'messages' and 'queue'
            var redisPubSub = new RedisPubSubServer(clientsManager, "messages","queue")
            {
                OnUnSubscribe = (channel) =>
                {
                    Console.WriteLine("Unsubscribed from channel '{0}'", channel);
                },
                OnMessage = (channel, msg) =>
                {
                    Console.WriteLine("Received '{0}' from channel '{1}'", msg, channel);
                }
            };
            redisPubSub.Start();

            //...
            //other code which takes ~5s after which i want to unsubscribe from 'messages'
            Thread.Sleep(5000); 
            //...

            //no longer require channel 'messages'. what to do here?

            while (true) ;//continue with other code
        }
    }
}

2 个答案:

答案 0 :(得分:1)

调用Stop()或Dispose()将取消订阅并停止收听订阅的频道。如果您想稍后再次开始收听,请使用Stop();如果您已完成RedisPubSubManager,请使用Dispose()。

答案 1 :(得分:0)

感谢mythz和一些研究对我有用:

取消订阅'消息'请使用此 - >

//reassign channels to just 'queue' removing 'messages' as a channel
redisPubSub.Channels = new string[] {"queue" };

取消订阅所有频道请使用此 - >

redisPubSub.Channels = new string[] { };//empty channel array