node.js - 在 node.js 中执行多个 redis 查询的更简洁的方法

标签 node.js redis

我做了一些 node.js 代码来检索 redis 数据库中的数据,但我不是很高兴,我想改进它...
基本上,我的 redis 数据库中有一条记录“people”。从“people”中,我得到一个“person:i”列表(i 是一个整数),对于每个“person:i”,我进行了额外的查询以检索具有键“person:i”的散列。

我是这样做的:

db.smembers("people", function(err1, people){
  var jsonObj;
  var jsonArr = [];
  if(!err1) {
    var i = 0;
    res.writeHead(200, {'content-type': 'application/json'});
    // people will provide a list like [person:1, person:2, ..., person:n]
    people.forEach(function(person){
      // In redis I get the hash with key "person:i" 
      db.hgetall(person, function(err2,obj){
        if(!err2){
          // Add person into array
          jsonArr.push({ "id" : person.substring(7), "lastname" : obj["lastname"], "firstname" : obj["firstname"]});

          // I'm not happy with this part where I check if I reached the last item of people array....
          i = i + 1;
          if(i == people.length){
            res.write(JSON.stringify(jsonArr));
            res.end();
          }
        } else {
          var jsonObj = { "error" : "database error", "message" : "Cannot get hash " + person}; 
          res.write(JSON.stringify(jsonObj));
          res.end();
        }
      });
    });
  } else {
    jsonObj = { "error" : "database error", "message" : err1.message };
    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify(jsonObj));
    res.end();
  }
});

最干净(至少更干净)的方法是什么?

最佳答案

您正在寻找的是一个异步控制流系统。一个例子是 Stepstreamline.js .

另一种方法是抽象流程,为 Person 创建一个数据模型来获取单个 person 对象,以及一个 People 模型,它是 Persons 的集合,其中包含一个方法,用于按照您的结构获取多个人使用。

编辑:我找到了 Node 兼容控制流/异步库的完整列表:https://github.com/joyent/node/wiki/modules#wiki-async-flow

编辑:在查看您的代码后,我想到了另一种替代方法,该方法非常适合这种情况,但不直接解决问题的控制流性质。

通过更改您的模式以仅将人员的 ID 存储在 people 键中,您可以使用 redis 的 SORT命令,这将使整个集合能够在单个命令中获取。要在 Redis 中执行此操作:

> SADD people 1 2 3 4
> HMSET person:1 firstname John lastname Smith
> HMSET person:2 firstname Jane lastname Smith
> HMSET person:3 firstname John lastname Doe
> HMSET person:4 firstname Jane lastname Doe
> SORT people GET # GET person:*->firstname GET person:*->lastname
 1) "1"
 2) "Jane"
 3) "Doe"
 4) "2"
 5) "Jane"
 6) "Smith"
 7) "3"
 8) "John"
 9) "Doe"
10) "4"
11) "Jane"
12) "Doe"

这在 people 键中有节省内存的额外好处,并且可以通过 SORT 命令的 by 启用分页/排序>限制选项。

关于node.js - 在 node.js 中执行多个 redis 查询的更简洁的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8224548/

相关文章:

javascript - Node/Express 路由不等待 Redis 服务器回调

redis更新具有相同值和ttl的键

javascript - 如何将Uint8ClampedArray转换为 Node 式Buffer;

javascript - 如何使用node.js在mongoose(mongodb)中的数组上执行 "join"?

java - 从同一台机器访问最快的 NoSql 数据库是哪个?

redis - 超过Redis maxmemory

redis - Redis 中键值对的存储方式

node.js - NodeJS、N-API、nan、node-gyp 和 cmake-js 之间的区别

node.js - 有没有办法在 503 错误后自动重启 Nodejs 应用程序?

javascript - process.nextTick 中未定义回调