cogitoergosum
cogitoergosum

Reputation: 2471

NodeJS - Redis connection events

My aim is as follows:

I can get the first two to work. But, I am not sure, how to handle other events of Redis elsewhere in my project source.

Example:

connect-once.js I am connecting with async so that the calling function can await for connection completion.

const redis = require('redis')
//
async function clientOperations(options) {
    let connObject = {}
    let redisClient = redis.createClient(options)
    return new Promise((resolve, reject) => {
        redisClient.on('error', (err) => {
            connObject = {
                cacheClient: {},
                connected: false
            }
            reject(connObject)
        })
        //
        redisClient.on('connect', () => {
            connObject = {
                cacheClient: redisClient,
                connected: true
            }
            resolve(connObject)
        })
    })
}
//
async function connect(options) {
    return new Promise(async (resolve, reject) => {
        try {
            let p = await clientOperations(options)
            resolve(p)
        } catch(e) {
            reject(e)
        }
    })
}
//
module.exports = { connect }

init.js

const cache = require('connect-once')
let cacheClient = await cache.connect()
//
const bizlogic = require('some-biz-logic')
await bizlogic.addcustomer({cacheClient : cacheClient, payload : express.req.payload})

In the above snippet, what happens when Redis connection drops while in bizlogic.addcustomer? Maybe, I am thinking too 'procedural programming'. I am curious to know how do I connect once, share the connection with rest of the project and handling any connection errors while using that connection somewhere in the project.

Upvotes: 2

Views: 9436

Answers (1)

arunp9294
arunp9294

Reputation: 777

I would suggest use ioredis over redis npm i ioredis https://github.com/luin/ioredis#auto-reconnect

By default, ioredis will try to reconnect when the connection to Redis is lost except when the connection is closed manually by redis.disconnect() or redis.quit().

Its very flexible to control how long to wait to reconnect after disconnection using the retryStrategy option:

var redis = new Redis({
  // This is the default value of `retryStrategy`
  retryStrategy: function(times) {
    var delay = Math.min(times * 50, 2000);
    return delay;
  }
});

Example connect-once.js

const Redis = require('ioredis');

let connObject;

//
async function clientOperations(options) {
    if (connObject && connObject.connected) {
        return connObject;
    }
    let redisClient = Redis({
        host: options.host,
        port: options.port,
        password: options.password,
        lazyConnect: true,
    });
    await redisClient.connect();
    connObject = {
        cacheClinet: redisClient,
        connected: true
    }
    return connObject;
}

//
async function connect(options) {
    return clientOperations(options);
}
//
module.exports = { connect }

Upvotes: 6

Related Questions