带节点的Redis成员 [英] Redis smembers with node
问题描述
我有一个 Node,Express和Websockets
聊天应用程序.当前在聊天室中的用户的用户名存储在 Redis
中.当我输入 SMEMBERS'onlineUsers'
时,从 redis-cli
中,我会返回当前房间中所有用户的列表:
I have a Node, Express, and Websockets
chat app. The usernames of the users currently in the chatroom is stored to Redis
. From the redis-cli
when I type in SMEMBERS 'onlineUsers'
, I get back a list of all the users currently in the room:
127.0.0.1:6379> smembers 'onlineUsers'
1) "jackson"
2) "bubba yump"
3) "dog"
4) "rumba"
5) "buba"
在主应用程序 javascript
文件中,我有一种获取当前用户的方法,因此可以在页面上显示他们:
In my main application javascript
file I have a method to get the current users so I can display them on the page:
var showCurrentUsers = function(){
$('#list_of_users').empty();
$.getJSON('getUsers', function(data){
console.log(data)
for (var i in data){
$('#list_of_users').append("<li> User: "+data[i]+"</li>")
}
});
}
在我的 Node
服务器文件中,我具有匹配的路由,但是 db.smembers
始终返回 true
而不是用户列表.
In my Node
server file I have the matching route but db.smembers
keeps returning true
instead of a list of the users.
app.get('/getUsers', function(req,res){
res.send(getOnlineUsers());
});
// REDIS DATA
var getOnlineUsers = function(){
return db.smembers("onlineUsers")
}
,这是用户名最初发布到数据库的位置:
and here is where the username is originally posted to the database:
client.on("setUsername", function(user){
pub.publish("chatting","A new user in connected:" + user);
db.sadd("onlineUsers",user);
}
);
我知道用户名已正确发布到数据库,并且可以从 redis-cli
访问它们,但是我不确定为什么我的JSON调用返回 true
而不是列表.
I know that the usernames are correctly posting to the database, and I can access them from the redis-cli
, but I'm not sure why my JSON call is returning true
instead of the list.
推荐答案
(我假设您正在使用 https://github.com/mranney/node_redis )
节点redis客户端是异步的.您可以将其视为写入和删除的同步,但是要从数据库读取数据,您需要使用回调.
The node redis client is async. You can treat it as sync for writes and deletes, but to read from the db you need to use a callback.
app.get('/getUsers', function(req, res, next){
getOnlineUsers(function (err, onlineUsers) {
if (err) {
return next(err);
}
res.send(onlineUsers);
});
});
// REDIS DATA
var getOnlineUsers = function(cb){
return db.smembers("onlineUsers", cb);
}
这篇关于带节点的Redis成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!