ServiceStack.Redis.RedisClient UnSubscribe函数挂起

时间:2015-05-04 18:50:00

标签: c# redis servicestack publish-subscribe

我尝试使用RedisPubSubServer,但这不适用于密钥通知,因为我需要订阅模式指定的频道。所以我创建了自己的解决方案:

public class RedisKeySubscriber
{
    public string Host { get; private set; }
    public int Port { get; private set; }

    private readonly Dictionary<string, IRedisSubscription> _subscriptions;

    public RedisKeySubscriber(string host, int port)
    {
        Host = host;
        Port = port;
        _subscriptions = new Dictionary<string, IRedisSubscription>();
    }

    public void Subscribe(string key, Action<string, string> handler)
    {
        lock (_subscriptions)
        {
            IRedisSubscription subscription;
            if (_subscriptions.TryGetValue(key, out subscription))
                return;

            // FIXME this might potentially create too many threads
            var client = new ServiceStack.Redis.RedisClient(Host, Port);
            subscription = client.CreateSubscription();
            subscription.OnMessage = handler;
            _subscriptions.Add(key, subscription);
            new Thread(() => subscription.SubscribeToChannelsMatching(key)).Start();
        }
    }

    public void Unsubscribe(string key)
    {
        lock (_subscriptions)
        {
            IRedisSubscription subscription;
            if (!_subscriptions.TryGetValue(key, out subscription))
                return;
            subscription.UnSubscribeFromChannelsMatching(key);
            _subscriptions.Remove(key);
        }
    }

    public void UnsubscribeAll()
    {
        lock (_subscriptions)
        {
            foreach (var subscription in _subscriptions)
                subscription.Value.UnSubscribeFromChannelsMatching(subscription.Key);
            _subscriptions.Clear();
        }
    }

    public void Dispose()
    {
        UnsubscribeAll();
    }
}

我意识到这会挂起PSUBSCRIBE命令。其他一切都很好。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我使用额外的“控制”频道解决了这个问题。因此,处理程序既可以订阅匹配'key'的通道,也可以订阅像'CHCTRL:guid'这样的通道,其中guid是类实例创建的特定GUID。取消订阅功能在CHCTRL:guid上发布消息,处理程序可以理解是时候取消订阅,因为消息不是来自'key'。

替代和建议的解决方案是不使用ServiceStack.Redis。