What is the best practice of using redis in nodejs?

I am building an application with nodejs, express and node_redis . I want to make a module to encapsulate all redis-related operations, so I don’t need to deal with redis keys everywhere.

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

Then I have two problems.

  • I want to create a redis connection and select a database:

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

    Since it selectis an asynchronous call, how can I use it in a separate module ( db.js)?

  • It looks like it client.quite()should be called before the script completes, or the script is not completed. How can I do this outside db.jswhile clientencapsulated as a local variable in db.js?

+3
source share
1 answer

- // , .

, 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

- UserService var . , UserService . UserService .

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

:

+3

All Articles