在redis中存储嵌套的javascript对象 - NodeJS [英] Storing nested javascript objects in redis - NodeJS
问题描述
我最近在nodejs中从memcached切换到redis。我在node-memcached中喜欢的是我可以将整个javascript对象保存在内存中。可悲的是,我无法用redis做到这一点。例如,我得到了以下对象:
I recently switched from memcached to redis in nodejs. The thing I liked in node-memcached was that I can save the whole javascript object in the memory. Sadly I couldn't do this in redis. For example, I got the following object:
var obj = {
name: "Hello world!",
author: "admin",
user: {
"yolololo" : {
"id": "352asdsafaseww",
"server": 5,
"data" : {
x: 1,
y: 1,
z: 50
}
},
"yolol" : {
"id": "358dsa",
"server": 7
}
}
}
3rd-Eden / node-memcached 我可以做:
memcached.set("obj", obj, 12345, function(err) { });
然后
memcached.get("obj", function(err, data) {
console.log(data);
});
我会得到我保存的对象,就像它一样。
And I'll get the object I saved, just the way it is.
redis的问题在于,如果我像这样保存对象:
The problem with redis is that if I save the object like this:
redisclient.set("obj", obj, redis.print);
当我用
redisclient.get("obj", function(err, data) {
console.log(data);
});
输出只是包含 [object Object] $ c $的字符串C>。
是的,我理解redis是基于文本的协议,它正在尝试做obj.toString(),但似乎memcached负责对象而redis没有。
我以为我可以做:
Yeah I understand redis is text-based protocol and it's trying to do obj.toString(), but seems memcached take care of objects and redis don't. I thought I could just do:
redisClient.set("obj", JSON.stringify(obj));
但我不确定这是不是很好,因为会有疯狂的高I / O我不确定JSON obj->字符串是否会成为瓶颈(10k +请求/秒)。
but I'm not sure if this will be good, because there will be insane high I/O and I'm not sure if the JSON obj->string will be bottleneck ( 10k+ request/second ).
Memcached和Redis都将数据存储为字符串,但是redis有内置的转换对象功能吗?
Both Memcached and Redis store the data as string, but does redis have built-in feature for converting objects?
推荐答案
- 字符串
- 列表
- 设置
- 哈希
- 分类集
- String
- List
- Set
- Hash
- Sorted set
您需要在 redis 和 memcached 。
node-memcached 自动解析/字符串化数据。但 node-redis 不会。
但是,您可以为您的应用程序实现自己的序列化/反序列化功能。
However, you can implement your own serialization/deserialization functions for your app.
node-memcached 对对象进行字符串化的方式是如下:
The way node-memcached stringifies an object is as follows:
if (Buffer.isBuffer(value)) {
flag = FLAG_BINARY;
value = value.toString('binary');
} else if (valuetype === 'number') {
flag = FLAG_NUMERIC;
value = value.toString();
} else if (valuetype !== 'string') {
flag = FLAG_JSON;
value = JSON.stringify(value);
}
它还解析检索到的文本这种方式:
It also parses the retrieved text this way:
switch (flag) {
case FLAG_JSON:
dataSet = JSON.parse(dataSet);
break;
case FLAG_NUMERIC:
dataSet = +dataSet;
break;
case FLAG_BINARY:
tmp = new Buffer(dataSet.length);
tmp.write(dataSet, 0, 'binary');
dataSet = tmp;
break;
}
这篇关于在redis中存储嵌套的javascript对象 - NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!