2
我正在使用服務堆棧連接到Redis並使用SubPub功能。IRedis訂閱連接
我應該保持IRedisSubscription和IRedisClient的實例化嗎?例如,我應該將它分配給一個類級別的變量?
或者我可以簡單地將其範圍在using語句中,Service Stack將處理持久性?
也就是說,它的下面的例子是正確的:
公共類RedisPubSub1:IDisposable的{
private static PooledRedisClientManager ClientPool = new PooledRedisClientManager("connectionString"); private IRedisSubscription _subscription; private IRedisClient _client; private Action<string, string> _publish; public event Action<string, string> Publish { add { _publish += value; } remove { _publish -= value; } } public RedisPubSub1() { Task.Factory.StartNew(() => { _client = ClientPool.GetClient(); _subscription = _client.CreateSubscription(); { _subscription.OnMessage = EnqueEvent; _subscription.SubscribeToChannels(new string[] { Channel }); } }); } private void EnqueEvent(string channel, string message) { if (_publish!= null) _publish(channel, message); } public void Dispose() { _subscription.Dispose(); _client.Dispose(); } } }
或者
公共類RedisPubSub2 {
private static PooledRedisClientManager ClientPool = new PooledRedisClientManager("connectionString"); private Action<string, string> _publish; public event Action<string, string> Publish { add { _publish += value; } remove { _publish -= value; } } public RedisPubSub2() { Task.Factory.StartNew(() => { using(var _client = ClientPool.GetClient()) { using(_subscription = _client.CreateSubscription() { _subscription.OnMessage = EnqueEvent; _subscription.SubscribeToChannels(new string[] { Channel }); } } }); } private void EnqueEvent(string channel, string message) { if (_publish!= null) _publish(channel, message); } }
謝謝!我想知道爲什麼這個電話被阻塞了,現在有道理。 – swestner
嗨,我有一個問題,如果redis服務器重新啓動會怎麼樣,它會阻止阻塞並繼續前進?我們注意到,訂閱在redis服務器重新啓動後停止接收消息。我最初的計劃是循環訂閱,以便訂戶可以恢復丟失的連接。 – CodeLinguist
@CodeLinguist該API映射接近Redis Pub/Sub命令,上面的示例不包括失敗的redis服務器實例的任何自動重試邏輯。您可以使用[ServiceStack.Redis RedisPubSubServer](https://github.com/ServiceStack/ServiceStack.Redis#managed-pubsub-server)進行託管訂閱,該託管訂閱將在失敗的連接上自動重新連接。 – mythz