XMen
XMen

Reputation: 30256

How to separate redis database for same two app in node.js

I have two same app running on different one for demo and one for developement .and m using the redis database to store key value, how can i seperate redis database for these two different app. m using node.js for redis client. and m using this https://github.com/mranney/node_redis/ redis client.

how to seperate redis database for same app in node.

Upvotes: 15

Views: 24638

Answers (2)

kotsy
kotsy

Reputation: 31

In 2024 with redis 7.4.1 you can select the database while connecting:

You can check the stage or set different environment variables for the database number (e.g. 0 for PROD and 1 for DEV)

import { createClient } from 'redis';
const databaseNumber: number = parseInt(process.env['REDIS_DB_NUMBER'] ?? '0', 10);
const redisClient = createClient({ url: redisUrl, database: databaseNumber });

Upvotes: 1

slickplaid
slickplaid

Reputation: 1431

You can use the .select(db, callback) function in node_redis.

var redis = require('redis'),
db = redis.createClient();

db.select(1, function(err,res){
  // you'll want to check that the select was successful here
  // if(err) return err;
  db.set('key', 'string'); // this will be posted to database 1 rather than db 0
});

If you are using expressjs, you can set a development and production environment variable to automatically set which database you are using.

var express = require('express'), 
app = express.createServer();

app.configure('development', function(){
  // development options go here
  app.set('redisdb', 5);
});

app.configure('production', function(){
  // production options here
  app.set('redisdb', 0);
});

Then you can make one call to db.select() and have the options set for production or development.

db.select(app.get('redisdb'), function(err,res){ // app.get will return the value you set above
  // do something here
});

More information on dev/production in expressjs: http://expressjs.com/guide.html#configuration

The node_redis .select(db, callback) callback function will return OK in the second argument if the database is selected. An example of this can be seen on the Usage section of the node_redis readme.

Upvotes: 32

Related Questions