Redis connections keep closing and opening (Node-Redis)

16 Views Asked by At

I am using Node-Redis package to connect to my Redis DB. Since I don't want to open and close a connection for each query. I am using a singleton pattern implemented with a IIEF implementation.

var RedisClient = (function () {
    var _redisClient: any = null;

        /**
     * Handles redis errors
     */
    var _clientReadyHandler = function () {
        const currentdate = new Date();
        Logger.infoMessage(`Redis Client Ready ${currentdate}`);
    };

    /**
     * Handles redis errors
     * @param {object} error
     */
    var _errorHandler = function (error) {
        const currentdate = new Date();
        Logger.errorMessage(`Redis Client Error ${currentdate} : ${error}`);
    };

    /**
     * Handles redis errors in reconnecting
     */
    var _reconnecting = function () {
        const currentdate = new Date();
        if (arguments[0]?.attempt > 1) {
            Logger.errorMessage(
                `Redis reconnecting issue ${currentdate} attempt ${
                    arguments[0]?.attempt
                } : ${JSON.stringify(arguments)}`
            );
        }
    };

    var pub: RedisClientType = {
        /**
         * Creates a redis connection
         */
        async createRedisClient() {
            if (_redisClient != null && _redisClient?.isReady) return;

            _redisClient = await createClient({
                url: REDISDBConfig.redisConnectionURL,
                name: REDISDBConfig.connectionName,
            });

            // Attach on ready handler
            _redisClient.on('ready', _clientReadyHandler);

            // Attach error handler
            _redisClient.on('error', _errorHandler);

            // Reconnecting
            _redisClient.on('reconnecting', _reconnecting);

            return await _redisClient.connect();
        },

        /**
         * Gets the object from Redis identifier
         */
        async getKeyValue(key: string) {
            if (_redisClient == null || !_redisClient?.isReady) {
                await pub.createRedisClient();
            }

            try {
                const value = await _redisClient.get(key);
                return JSON.parse(value);
            } catch (error) {
                Logger.errorMessage(error);
            }
        },
                // Other functions (scan, set, del ...)


          return pub;
})();

export default RedisClient;

Logs of redis connection open and closing frequency](https://i.stack.imgur.com/NchrL.png)

I would like to know why it seems to reconnect non-stop.

0

There are 0 best solutions below