charlee
charlee

Reputation: 1369

What is the best practice for using redis in nodejs?

I'm building an app with nodejs, express and node_redis. I want to make a module to encapsule all the redis-related operations so that I don't have to deal with redis keys everywhere.

|- app.js
|- models
|   |- db.js   <-- All redis-related operations here
.....

Then I have two problems here.

  1. I want to create the redis connection and select a database:

    var redis = require('redis');
    var client = redis.createClient();
    client.select(config.database, function() {
        // actual db code
    });
    

    Since select is an async call, how could I use it in a separate module (db.js)?

  2. Looks like client.quite() must be called before the script ends, or the script won't quit. How could I do this outside db.js while client is encapsuled as a local variable in db.js?

Upvotes: 6

Views: 8375

Answers (2)

Tlaloc-ES
Tlaloc-ES

Reputation: 5282

I use this

lib/redisClient.js

import redis from "redis";

let _redisClient;

const redisClient = {
  createClient(uri)  {
    if (!_redisClient){
      console.log('Redis conexion created')
    _redisClient = redis.createClient(uri);
    }
    return _redisClient;
  },
  close(): void {
    _redisClient.close();
  }
};

export default redisClient;

index.js

import redisClient from "./lib/RedisClient"
...
const client = redisClient.createClient(process.env.REDISURI)
const clientA = redisClient.createClient(process.env.REDISURI)
...

And this only creates one connexion so you only get:

Redis connexion created

Instead of

Redis connexion created

Redis connexion created

Upvotes: 1

dumitru
dumitru

Reputation: 379

I suggest to make something like a service/repository/interface with a defined interface, then call it's methods.

For example, if you have a users db:

var UserService=function(){
  this.client=new ...
}

UserService.prototype.getUserById=function(id, cb){
this.client.select(...,function(result,err){
  cb(result);
}
}

UserService.prototype.... so on

Now in your express app you will create an UserService var and use it. Of course, you should create UserService smarter. In UserService, then you can add cache.

var app = express();
var userService = new UserService();
//...

For closing read this: Do I need to quit

Upvotes: 3

Related Questions