来自:网络,侵删
string
hash
I want to store a JSON payload into redis. There's really 2 ways I can do this:
1. One using a simple string keys and values.
key:user, value:payload (the entire JSON blob which can be 100-200 KB)
SET user:1 payload
2. Using hashes
HSET user:1 username "someone"
HSET user:1 location "NY"
HSET user:1 bio "STRING WITH OVER 100 lines"
Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.
Which is more memory efficient? Using string keys and values, or using a hash?
https://redis.io/topics/memory-optimization
,用来理解官方的开发者是内存优化方面基于什么考虑。INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
优势:可以认为是“佳实践”,因为每个对象都是全特性的key,JSON解析特别块,尤其是一次性查询很多个字段的时候 劣势:如果只查询一个字段,速度就显得比较慢了
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
优势:这也可以认为是佳时间。每个对象都是一个全特性的key。不需要解析JSON字符串 劣势:如果要查询对象的全部字段会比较慢。嵌套类型的对象(即对象里面还包着对象)无法轻易存储
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
优势:JSON解析很快,尤其是一次查询多个字段时,对主key的命名空间污染更少 劣势:如果要存储很多对象,那么内存使用和方案1相当。当只需要查询一个字段时,会比方案2速度慢。答者不认为这是一个“佳实践”
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
优势:对象的属性是全特征key,对于应用来说比较好处理 劣势:慢,内存消耗更大,不是一个“佳实践”。对主key的命名空间有很大污染