node.js 我应该如何在 redis 中存储 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8986982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I store JSON in redis?
提问by tofutim
I have JSON (<1k) to store in Redis through node.js. What are the pros and cons of storing it as an object or string? Are there other options I missed? All processing will ultimately happen on the client side, so converting into an object is not necessary.
我有 JSON (<1k) 通过 node.js 存储在 Redis 中。将其存储为对象或字符串的优缺点是什么?我错过了其他选择吗?所有的处理最终都会发生在客户端,所以没有必要转换成一个对象。
SET
放
var images = JSON.parse(data); // data is already JSON, is this needed?
callback(images); // sends result to the user
r.set('images:' + req.query, images); // saving the object
GET
得到
callback(images);
回答by yojimbo87
You can store JSON in redis either as a plain string in dedicated key (or member/value of a set/list) or in a hashstructure. If you look at node_redisdocs into Friendlier hash commandspart you'll see that it gives you some useful methods for manipulating JSON based data. Pros of this approach is that it allows you to get/set only part of the original object and it might also consume less memorycompared to plain strings.
您可以将 JSON 作为专用键(或集合/列表的成员/值)或散列结构中的纯字符串存储在 redis 中。如果您将node_redis文档查看到Friendlier hash commands部分,您会发现它为您提供了一些有用的方法来操作基于 JSON 的数据。这种方法的优点是它允许您只获取/设置原始对象的一部分,并且与普通字符串相比,它也可能消耗更少的内存。
回答by Akash Babu
You could use this library redis-json
你可以使用这个库redis-json
Sample usage example:
示例用法示例:
import Redis from 'ioredis';
import JSONCache from 'redis-json';
const redis = new Redis();
const jsonCache = new JSONCache(redis)
const user = {
name: "test",
age: 21,
gender: "male"
}
await jsonCache.set('123', user)
const result = await jsonCache.get('123')
This library stores the json in Hash set.
该库将 json 存储在 Hash 集中。
It also supports retreival of a single or a set of keys, i.e.
它还支持检索单个或一组密钥,即
await jsonCache.get('123', "age", "name")

