赞
踩
Redis 中的 Hash 数据 是一个 键值对集合 , 类似于 Java 中的 Map 集合 ;
Hash 数据底层数据结构是 :
Redis 中存储对象的方式 :
存储序列化之后的数据 : 将 对象 序列化为 json 字符串 , 然后 存储到 Redis 键值对 的 Value 值中 ;
直接存储对象字段 : 将每个对象的字段拆开 , 进行分开存储 , 非常繁琐 ;
使用 Hash 存储 ( 推荐 ) : 将 对象 的 字段 , 都以 Hash 的 键值对 形式存储起来 , 可以直接访问修改对应的对象字段 ;
键值对区分 : Redis 中的键值对 一般称为 Key=Value , 在 Hash 中的键值对 一般称为 Field=Value ;
执行
hget student name
命令 , 可以 获取 Redis 中 student 键 对应的 Hash 数据中的 name 键 对应的 值 ;
代码示例 :
127.0.0.1:6379> hset student name Tom
(integer) 1
127.0.0.1:6379> get student
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> hget student
(error) ERR wrong number of arguments for 'hget' command
127.0.0.1:6379> hget student name
"Tom"
127.0.0.1:6379>
注意 : 读取该 Hash 的 name=Tom 键值对 时 , 需要使用 hget student name 命令 ;
执行
hexists student name
命令 , 可以 获取 Redis 中 student 键 对应的 Hash 数据中的 name 键 是否存在 ;
代码示例 :
127.0.0.1:6379> hexists student name
(integer) 1
127.0.0.1:6379> hexists student name1
(integer) 0
127.0.0.1:6379>
执行
hkeys student
命令 , 可以 获取 Redis 中 student 键 对应的 Hash 数据中的 所有 键 Field ;
代码示例 :
127.0.0.1:6379> hkeys student
1) "name"
2) "age"
127.0.0.1:6379>
执行
hvals student
命令 , 可以 获取 Redis 中 student 键 对应的 Hash 数据中的 所有 值 ;
代码示例 :
127.0.0.1:6379>
127.0.0.1:6379> hvals student
1) "Tom"
2) "18"
127.0.0.1:6379>
执行
hset student name Tom
命令 , 可以 给 键 student 中的 Hash 数据值 中 添加 name=Tom 键值对 ;
代码示例 : 向 Redis 的 student 键值 下 插入 name=Tom 键值对 ;
127.0.0.1:6379> hset student name Tom
(integer) 1
127.0.0.1:6379> get student
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> hget student
(error) ERR wrong number of arguments for 'hget' command
127.0.0.1:6379> hget student name
"Tom"
127.0.0.1:6379>
注意 : 读取该 Hash 的 name=Tom 键值对 时 , 需要使用 hget student name 命令 ;
执行
hmset student name Tom age 18
命令 , 可以 给 键 student 中的 Hash 数据值 中 添加 name=Tom 和 age=18 键值对 ;
代码示例 : 向 Redis 的 student 键值 下 插入 name=Tom 和 age=18 键值对 ;
127.0.0.1:6379> hmset student name Tom age 18
OK
127.0.0.1:6379> hget student age
"18"
127.0.0.1:6379> hget student name
"Tom"
127.0.0.1:6379>
执行
hincrby student age -5
命令 , 可以 给 键 student 中的 Hash 数据值 中 age=18 数据中的值 -5 操作 ;
代码示例 :
127.0.0.1:6379>
127.0.0.1:6379> hincrby student age -5
(integer) 13
127.0.0.1:6379> hvals student
1) "Tom"
2) "13"
127.0.0.1:6379>
执行
hsetnx student weight 85
命令 , 可以 在 键 student 中的 Hash 数据值 中 如果不存在 weight 键 , 则 添加 weight=85 键值对数据 ;
代码示例 :
127.0.0.1:6379>
127.0.0.1:6379> hsetnx student weight 85
(integer) 1
127.0.0.1:6379> hkeys student
1) "name"
2) "age"
3) "weight"
127.0.0.1:6379>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。