2011-06-03 207 views
2

我有以下代碼。如何獲得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); 
}); 

我想獲得所有的用戶列表我怎麼可以讓所有用戶列出這個我試過但它不工作。

回答

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

,如果你不需要在第二個散列值的任何數據,您應該考慮使用一個列表,而不是,

+0

我已經完成了client.keys(「users *」) – XMen 2011-06-04 07:35:34

+1

您應該謹慎使用該函數。這是一個非常好的功能,但它也是Redis中速度最慢的功能之一。因此,它有機會拖動您的網站性能。如果你想這樣做,那麼你應該使用一套。 – Colum 2011-06-04 11:19:57

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

看起來很有趣,那麼如何讓一個特定的用戶成爲一名? – XMen 2011-06-28 12:15:58

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); 
}); 
相關問題