node.js store objects in redis
Since the socket is of type Object
, you need to convert the object to a string before storing and when retrieving the socket, need to convert it back to an object.
You can use
JSON.stringify(socket)
to convert to a string and
JSON.parse(socketstr)
to convert back to an object.
Edit:
Since the release of version 2.0.0
, we are able to store objects as hashes into Redis.
client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");
client.hgetall("hosts", function (err, obj) {
console.dir(obj);
});
https://redis.io/commands/hset
https://github.com/NodeRedis/node_redis
Downvoters: the context here is SET command and ability to store arbitrary objects.
No, you can't do that. You should accept the fact that Redis stores everything as a string (the protocol is text-based, after all). Redis may perform some optimizations and convert some values to integers, but that's its business, not yours.
If you want to store arbitrary objects in Redis, make sure that you serialize them before saving and de-serialize after retrieving.
I'm not sure if you can do that with socket objects, though. They simply describe a system resource (an open connection), after all (TCP sockets, for example). If you manage to serialize the description and deserialize it on another machine, that other machine won't have the connection.
The solution below doesn't solve the whole point of using redis -- to share data across cluster instances. Storing an instance-specific id in redis will be meaningless to another instance that tries to use that id.
However, there is "hmset" which can be called with an object and it will set each object field as a separate redis field in the same key. And it will be converted back to an object when you call hgetall. Unfortunately, I don't think it handles nested objects or arrays within an object, only simple properties whose values can be stored by "toString()".
So an object like
client.hmset("myhashkey",{a:1, b:2, c:'xxx'})
works great and can be retrieved with
client.hmget("myhashkey", function(obj) {
console.log(obj);
});
Not so much for:
client.hmset("myhashkeynested",{a:1, b:2, c:'xxx', d: { d1: 'x', d2: 'y'}});
I also found this to be an incredibly useful tool, especially if you are channeling JSON from an API to your front-end:
node-redis-jsonify
If you're receiving a huge block of JSON and can't store as a specific hash, stringifying it while storing will allow you to retrieve the whole json instead of just "[object Object]".