Redis 哈希(Hash)

Hash 存对象字段,比把对象 JSON 塞进 String 更灵活。

Beginner
Key PointsHash 适合存对象:可单独读写某个字段,不用整体序列化。

读写字段

Shell
HSET user:1 name "alice" age 29 city "BJ"
HGET user:1 name
HGETALL user:1
HINCRBY user:1 age 1     # 字段原子 +1
HMGET user:1 name age
Output
1) "name"
 2) "alice"
 3) "age"
 4) "29"
 5) "city"
 6) "BJ"

Hash vs String

方案优点缺点
String 存 JSON整体读写简单改一个字段要整取整写
Hash可单独改字段、省带宽不能对整体设过期
A Hash field cannot itself be a Hash (no nesting). To expire, set EXPIRE on the Hash key — expiration is per-key regardless of internal structure.

Friends & Partners