redis订阅可实现性并重试

6ljaweal  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(287)

我在应用程序中使用servicestack.redis,我的订阅方法如下:

protected void Subscribe(string channelsToSubscribe)
        {
            using IRedisClient redisClient = new RedisClient('127.0.0.1', '6379');
            using var subscription = redisClient.CreateSubscription();
            subscription.OnMessage = (channel, msg) =>
            {
                // do something with the message
            };
            subscription.SubscribeToChannels(channelsToSubscribe);
        }

问题是:当我尝试订阅一个频道而redis离线时,我需要继续尝试,直到我有一个稳定的连接并正确订阅为止
所以我做了这个:

protected void Subscribe(string channelsToSubscribe)
        {
            try
            {
                using IRedisClient redisClient = new RedisClient('127.0.0.1', '6379');
                using var subscription = redisClient.CreateSubscription();
                subscription.OnMessage = (channel, msg) =>
                {
                    // do something with the message
                };
                subscription.SubscribeToChannels(channelsToSubscribe);
            }
            catch (Exception e)
            {
                // notify someone that an error happen
                Subscribe(channelsToSubscribe);
            }
        }

这是可行的,但是如果redis离线很长时间,递归堆栈在满的时候会抛出一个错误(stackoverflowexception)。
所以我将递归循环改为do while循环:

protected void Subscribe(string channelsToSubscribe)
        {
            using IRedisClient redisClient = new RedisClient('127.0.0.1', '6379');
            using var subscription = redisClient.CreateSubscription();
            do
            {
                try
                {
                    subscription.OnMessage = (channel, msg) =>
                    {
                        // do something with the message
                    };

                    subscription.SubscribeToChannels(channelsToSubscribe);
                }
                catch (Exception e)
                {
                    // notify someone that an error happen
                }
            } while (redisClient.Ping());
        }

但看起来 redisClient.Ping() 当redis也断开连接时抛出一个异常,我需要得到一个信息告诉我redis是否有稳定的连接,有人知道解决这个问题的方法吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题