redis 性能,将json对象存储为字符串 [英] redis performance, store json object as a string

查看:51
本文介绍了redis 性能,将json对象存储为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保存一个用户模型,例如:

I need to save a User model, something like:

{ "nickname": "alan",
  "email": ...,
  "password":...,
  ...} // and a couple of other fields

今天,我使用一个集合:用户
在这个集合中,我有一个像 user:alan
这样的成员在这个成员中,我有上面的哈希

Today, I use a Set: users
In this Set, I have a member like user:alan
In this member I have the hash above

这工作正常,但我只是想知道是否可以使用以下方法代替上述方法:

This is working fine but I was just wondering if instead of the above approach that could make sense to use the following one:

仍然使用users Set(方便​​获取用户(成员)列表)
在这个集合中只使用一个键/值存储,如:

Still use users Set (to easily get the users (members) list)
In this set only use a key / value storage like:

键:艾伦value : 上述用户哈希的字符串化版本

key: alan value : the stringify version of the above user hash

然后检索记录会更容易(然后我将不得不使用 JSON 解析它).

Retrieving a record would then be easier (I will then have to Parse it with JSON).

我对 redis 很陌生,我不确定什么是最好的.你怎么看?

I'm very new to redis and I am not sure what could be the best. What do you think ?

推荐答案

你可以使用Redis 哈希用于存储 JSON 对象字段和值的数据结构.例如,您的用户"集仍然可以用作存储所有用户的列表,并且您的个人 JSON 对象可以像这样存储到哈希中:

You can use Redis hashes data structure to store your JSON object fields and values. For example your "users" set can still be used as a list which stores all users and your individual JSON object can be stored into hash like this:

db.hmset("user:id", JSON.stringify(jsonObj));

现在您可以通过键获取所有用户或仅特定用户(从中获取/设置仅指定的字段/值).还有这些 两个问题可能与您的场景有关.

Now you can get by key all users or only specific one (from which you get/set only specified fields/values). Also these two questions are probably related to your scenario.

(抱歉我没有意识到我们之前讨论过这个)

然后检索记录会更容易(然后我将不得不使用 JSON 解析它).

Retrieving a record would then be easier (I will then have to Parse it with JSON).

这是真的,但是使用散列数据结构,您只能获取/设置您需要使用的字段/值.如果您只想更改对象的一部分(另一件事是您每次都需要对对象进行字符串化/解析),那么检索整个 JSON 对象可能会导致性能下降(取决于您执行的频率).

This is true, but with hash data structure you can get/set only the field/value which you need to work with. Retrieving entire JSON object can result in decrease of performance (depends on how often you do it) if you only want to change part of the object (other thing is that you will need to stringify/parse the object everytime).

这篇关于redis 性能,将json对象存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆