Redis hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。
Redis 中每个 hash 可以存储 232 - 1 键值对(40多亿)。
实例:
127.0.0.1:6379> HMSET runoobkey name "redis tutorial" description "redis basic commands for caching" likes 20 visitors 23000
OK
127.0.0.1:6379> HGETALL runoobkey
1) "name"
2) "redis tutorial"
3) "description"
4) "redis basic commands for caching"
5) "likes"
6) "20"
7) "visitors"
8) "23000"
1.1、hset、hmget
127.0.0.1:6379> hset myhash field v1 //set一个key-value
(integer) 1
127.0.0.1:6379> hget myhash field //获取一个字段值
"v1"
127.0.0.1:6379> hset myhash field2 v2 field3 v3 //set多个key-value
(integer) 2
127.0.0.1:6379> hmget myhash field2 field3 //获取多个字段值
1) "v2"
2) "v3"
127.0.0.1:6379> hgetall myhash //获取hash中全部数据
1) "field"
2) "v1"
3) "field2"
4) "v2"
5) "field3"
6) "v3"
1.2、hdel
127.0.0.1:6379> hgetall myhash
1) "field"
2) "v1"
3) "field2"
4) "v2"
5) "field3"
6) "v3"
127.0.0.1:6379> hdel myhash field //删除指定的key字段以及对应的value值。
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "field2"
2) "v2"
3) "field3"
4) "v3"
127.0.0.1:6379>
1.3、hlen
127.0.0.1:6379> hlen myhash //获取hash字段长度
(integer) 2
1.4、HEXISTS
127.0.0.1:6379> HEXISTS myhash foeld2 //判断hash中指定字段是否存在
(integer) 0
127.0.0.1:6379> HEXISTS myhash field2
(integer) 1
1.5、hkeys、hvals
127.0.0.1:6379> hkeys myhash //获取所有field
1) "field2"
2) "field3"
127.0.0.1:6379> hvals myhash //获取所有value
1) "v2"
2) "v3"
1.6、hincrby、hsetnx
127.0.0.1:6379> hset myhash field4 1
(integer) 1
127.0.0.1:6379> HINCRBY myhash field4 1 //指定增量
(integer) 2
127.0.0.1:6379> HINCRBY myhash field4 -2
(integer) 0
127.0.0.1:6379> HSETNX myhash hield5 v5//如果不存在可以设置,存在不可以设置
(integer) 1
127.0.0.1:6379> HSETNX myhash hield5 v6
(integer) 0
hash类型更适合对象的存储,String类型更是个字符串存储!!