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

后端 未结 1 1915
鱼传尺愫
鱼传尺愫 2021-02-03 10:24

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 tw

相关标签:
1条回答
  • 2021-02-03 10:59

    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.

    0 讨论(0)
提交回复
热议问题