如何让所有用户都使用redis

时间:2011-06-03 06:28:40

标签: node.js redis

我有以下代码。

var redis = require("redis"),
    client = redis.createClient();


user_rahul = { 
     username: 'rahul'

   };
user_namita = {
  username: 'namita'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
client.hgetall("users" , function(err, user) {
  console.log(user);
});

我想让所有用户列出我如何让​​所有用户列出我尝试过的但不起作用。

3 个答案:

答案 0 :(得分:5)

您正在使用自己的哈希设置用户,因此当您执行hgetall用户时,您将尝试获取用户哈希的所有成员。你应该这样做:

var redis = require("redis"),
client = redis.createClient();
user_rahul = { 
    username: 'rahul'
};
user_namita = {
    username: 'namita'
};
client.hset('users', user_rahul, 'Another Value, Pass Maybe?');
client.hset('users', user_namita, 'Another Value, Pass Maybe?');
var username = "rahul"; // From a POST perhaps
client.hgetall("users" , function(err, user) {
    console.log(user);
});

如果您不需要第二个哈希值中的任何数据,则应考虑使用列表

答案 1 :(得分:2)

这个怎么样

var flow = require('flow'); //for async calls
var redis = require("redis").createClient();

function AddUser(user,callback){
 flow.exec(
   function(){
     //AI for Keep unique
     redis.incr('nextUserId',this);
   },
   function(err,userId){
     if(err) throw err;
     this.userId = userId;
     redis.lpush('users',userId,this.MULTI()); 
     redis.hmset('user:'+userId+':profile',user,MULTI());
   },
   function(results){
      results.forEach(function(result){
    if(result[0]) throw result[0];
      });

     callback(this.userId);
   }
 );
}

user_rahul = {username: 'rahul'};
user_namita = {username: 'namita'};

//Add user
AddUser(user_rahul,function(userId){
    console.log('user Rahul Id' + userId);

});

AddUser(user_namita,function(userId){
    console.log('user Namita Id' + userId);

});


//users

function Users(callback){
var users = [];

 flow.exec(
    function(){
      redis.lrange('users',0,-1,this);
    },
    function(err,userIds){
      if(err) throw err;

     flow.serialForEach(userIds,function(userId){
        redis.hgetall('user:'+userId+':profile',this);
     },
     function(err,val){
       if(err) throw err;
       users.push(val);
     },
     function(){
      callback(users);
     });
    } 
 );
}


//call
Users(function(users){
   console.log(users);
});

答案 2 :(得分:0)

对于单个用户

function getUser(userId,callback){
 redis.hgetall('user:'+ userId +':profile',function(err,profile){
        if(err) throw err;
        callback(profile);  
    });
}   

getUser(1,function(profile){
    console.log(profile);
});