12

我有两个相同的应用程序在不同的应用程序上运行,一个用于演示,一个用于开发。m 使用 redis 数据库存储键值,我如何为这两个不同的应用程序分离 redis 数据库。m 使用 node.js 作为 redis 客户端。和 m 使用这个https://github.com/mranney/node_redis/ redis 客户端。

如何在节点中为同一应用程序分离 redis 数据库。

4

1 回答 1

26

您可以使用.select(db, callback)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
});

如果你使用的是 expressjs,你可以设置一个开发和生产环境变量来自动设置你使用的数据库。

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);
});

然后,您可以拨打一个电话db.select()并为production或设置选项development

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

有关 expressjs 中的开发/生产的更多信息:http: //expressjs.com/guide.html#configuration

node_redis .select(db, callback)如果选择了数据库,回调函数将在第二个参数中返回 OK 。这方面的一个例子可以在node_redis 自述文件的使用部分看到。

于 2011-06-10T10:51:53.503 回答