Redis subscriptions realiblity and retry

255 Views Asked by At

Im using ServiceStack.Redis in my application and i have my subscribe method is this:

        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);
        }

The problem: When i try to subscribe to a channel and redis is offline i need to keep trying till i have a stable connection and subscribe correctly

So i did this:

        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);
            }
        }

This works, but if redis is offline for a long time, the recursive stack will throw an error (StackOverflowException) when it gets full.

So i change the recursive to a do while loop:

    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());
        }

but it seems that the redisClient.Ping() throws an exception when the redis is disconnected too, i need to get a information telling me if the redis has an stable connection or not, anyone knows a solution for this?

0

There are 0 best solutions below