在redis中存储对象属性
假设我有一个对象(用户),其中包含一些属性(ID、姓名、姓氏、年龄)。哪种方式更好地将这个对象存储在redis中?
- 将每个属性值存储在专用键中,例如 user:{id}:id、user:{id}:name、user:{id}:surename、user:{id}:age
- 将整个 User 对象存储为 JSON 字符串键,例如 user:{id}:json (键的值将是这样的:{"ID": 123, "Name": "Johny", "Surename": "Bravo", "Age": 22 })
Lets say I have an object (User) which consists of a few properties (ID, Name, Surename, Age). Which way is better to store this object in redis?
- store each property value in dedicated key, for example user:{id}:id, user:{id}:name, user:{id}:surename, user:{id}:age
- store whole User object as JSON string in one key, for example user:{id}:json (value of the key will be something like this: {"ID": 123, "Name": "Johny", "Surename": "Bravo", "Age": 22})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 这些 两个 来源可能最佳解决方案是使用 哈希,因为在以 JSON 作为键值的场景中使用专用键和长字符串时会消耗内存。
According to these two sources probably the optimal solution would be to use hashes because of memory consumption when using dedicated keys and long string in scenario with JSON as key value.
来自官方 Redis
尽可能使用哈希
当你没有太多字段时,
From official Redis
Use hashes when possible
When you haven't to much fields in it.
根据我的测试,使用哈希占用的空间要小得多,但这就是唯一的原因。如果您有大量数据,请考虑使用哈希。否则,您也可以使用 JSON,因为如果您愿意,可以很容易将其序列化和反序列化为对象,并且可以进行一般处理。
From my tests using hash takes much smaller space, but that is about the only reason. If you have a lot of data consider using hash. Otherwise you might as well use JSON since it's easy to serialize and deserialize it to objects if you so wish, and handle in general.