在Node.js中,如何以编程方式从一个redis数据库中检索许多散列值,并使用一组作为索引

所以我在我的redis数据库中为每个用户都有一大堆字段,我希望能够检索所有logging并显示它们。 我这样做的方式是存储一组所有userids,当我想要所有的logging,我recursion地迭代设置抓住他们的logging使用集中的userids,并将它们添加到一个全局数组,然后最后返回这个全局数组。 无论如何,我不是特别喜欢这种方法,并希望听到一些替代scheme的build议,我觉得必须有更好的function在node.js或redis这个问题。 也许有一种方法可以完全避免使用这个设置,但是四处看看我什么都看不到。

这是我的psuedoish(相当完整的)node.js代码的一个例子,注意set的大小不是问题,因为它很less会大于15。

寄存器function:

var register = function(username, passwordhash, email){ // Get new ID by incrementing idcounter redis.incr('db:users:idcounter', function(err, userid){ // Setup user hash with user information, using new userid as key redis.hmset('db:user:'+userid, { 'username':username, 'passwordhash':passwordhash, 'email':email },function(err, reply){ // Add userid to complete list of all users redis.sadd('db:users:all', userid); } }); }); } 

logging检索function:var getRecords = function(fcallback){

  // Grab a list of all the id's redis.smembers('db:users:all', function(err, allusersids){ // Empty the returned (global) array completeArray = []; // Start the recursive function, on the allusersids Array. recursive_getNextUserHash(allusersids, fcallback); }); } 

用于检索单个logging的recursion函数:

 // Global complete Array (so recursive function has access) var completeArray = []; // recursive method for filling up our completeArray var recursive_getNextUserHash = function(userArray, callback){ // If userArray==0 this means we have cycled entire list, // call the callback, and pass it the completeArray which // is now full of our usernames + emails if(userArray.length==0){ callback.apply(this, [completeArray]); return; } // If still more items, start by popping the next user var userid = userArray.pop(); // grab this users information redis.hvals('db:user:'+userid, function(err, fields){ // Add users information to global array completeArray.push({username:fields[0],email:fields[2]}); // Now move on to the next user recursive_getNextUserHash(userArray, callback); }); } 

使用会是这样的:

 register('bob', 'ASDADSFASDSA', 'bob@example.com'); register('bill', 'DDDASDADSAD', 'bill@example.com'); getRecords(function(records){ for(var i=0;i<records.length;i++){ console.log("u:"+records[i]['username']+',@:'+records[i]['email']); } }); 

简介:什么是使用node.js和redis检索Hash的许多字段的好方法? 在写完这个问题之后,我开始怀疑这是否只是你在redis中的做法,你做了很多往返,不pipe是这种情况,一定有办法避免这个可怕的循环!

假设你使用的是https://github.com/mranney/node_redis – 看看Multi和Exec。 您可以在一个请求中发送所有的命令,并一次性等待所有的响应。 不需要recursion。

对于有类似问题的其他人,这里是我最终使用的语法:

 redis.smembers('db:users:all', function(err, reply){ var multi = redisClient.multi(); for(var i=0;i<reply.length;i++){ multi.hmget('db:user:'+reply[i], ['username', 'email']); } multi.exec(function(err, replies){ for(var j=0;j<replies.length;j++){ console.log("-->"+replies[j]); } }); });