Node.js 如何获取redis中的所有用户
我有以下代码Node.js 如何获取redis中的所有用户,node.js,redis,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 us
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);
});
我想获取所有用户列表如何获取所有用户列表这是我尝试过但不起作用的内容。您正在用户自己的哈希中设置用户,因此当您执行hgetall users时,您正在尝试获取用户哈希的所有成员。你应该做:
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);
});
你应该考虑使用一个列表,如果你不需要第二个散列值
中的任何数据,这个如何?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);
});
单用户
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);
});
你应该谨慎使用这个函数。这是一个非常好的函数,但也是Redis中速度最慢的函数之一。因此,它有机会拖累你的网站性能下降。如果你想这样做,那么你应该使用一个集合。看起来很有趣,那么获得一个特定的用户怎么样?