I am using redis server to store key-value(username-socketID) pairs for a chat app in socket.io.
我正在使用redis服务器为socket.io中的聊天应用程序存储键值(username-socketID)对。
The problem i have faced is that the same username can login from different devices so will have different socketIDs. SO i have to associate an array of socketIDs against one username. I was trying to associate an array to the key but itseems to be taking only the first element of the array as a string. Below is my code
我遇到的问题是相同的用户名可以从不同的设备登录,因此将具有不同的套接字ID。所以我必须将一个socketID数组与一个用户名相关联。我试图将数组与键相关联,但它似乎只是将数组的第一个元素作为字符串。以下是我的代码
Setting the array to the key:
将数组设置为键:
var socketIDs = [];
socketIDs.push(socket.id);
client.set(username, socketIDs, function (err) {
console.log("IN USERNAME EVENT" + username + ":" + socketIDs);
});
Getting the array from the key:
从密钥中获取数组:
client.get(username, function (err, socketIDs) {
var i = socketIDs.indexOf(socket.id);
if (i != -1)
{
socketIDs.splice(i, 1);
}
client.set(username, socketIDs, function (err) {
console.log(username + " DISCONNECTED");
socket.disconnect();
});
});
When am trying to fetch the value associated with the username, i get just the socketID as a string and not the array format that i had originally added as.
当我尝试获取与用户名关联的值时,我只将socketID作为字符串而不是我最初添加的数组格式。
Any fix for this? or what is the best way to approach my requirement of storing multiple values for a single key?
对此有任何修复?或者什么是满足我为单个密钥存储多个值的要求的最佳方法?
1 个解决方案
#1
3
I would recommend using a list
or a set
. I would use a list
unless you need duplication checks (if so then use a set
). All the following examples are list
based but you can find the equivalents for set
here.
我建议使用列表或集合。我会使用一个列表,除非你需要重复检查(如果是这样,那么使用一组)。以下所有示例均基于列表,但您可以在此处找到设置的等效项。
Adding a new socket ID
添加新的套接字ID
client.lpush(username, socket.id, function(err) {
console.log('Prepended new socket ID to list');
});
Getting all socket IDs for a user
获取用户的所有套接字ID
client.lrange(username, 0, -1, function(err, socketIds) {
});
Removing a given socket ID
删除给定的套接字ID
client.lrem(username, socketId, 0, function(err) {
});
(I've assumed you're using the node_redis
lib).
(我假设你正在使用node_redis lib)。
#1
3
I would recommend using a list
or a set
. I would use a list
unless you need duplication checks (if so then use a set
). All the following examples are list
based but you can find the equivalents for set
here.
我建议使用列表或集合。我会使用一个列表,除非你需要重复检查(如果是这样,那么使用一组)。以下所有示例均基于列表,但您可以在此处找到设置的等效项。
Adding a new socket ID
添加新的套接字ID
client.lpush(username, socket.id, function(err) {
console.log('Prepended new socket ID to list');
});
Getting all socket IDs for a user
获取用户的所有套接字ID
client.lrange(username, 0, -1, function(err, socketIds) {
});
Removing a given socket ID
删除给定的套接字ID
client.lrem(username, socketId, 0, function(err) {
});
(I've assumed you're using the node_redis
lib).
(我假设你正在使用node_redis lib)。