源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Redis中散列类型的常用命令小结

  • 时间:2021-06-30 10:19 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Redis中散列类型的常用命令小结
[b]Redis散列类型[/b] Redis是采用字典结构以键值对的形式存储数据的,而散列类型(hash)的键值也是一种字典结构,其存储了字段和字段值的映射,但字段值只能是字符串,不支持其他数据类型,也就是说,散列类型不能嵌套其他的数据类型。一个散列类型键可以包含至多2^32-1个字段。 除了散列类型,Redis的其他数据类型同样不支持数据类型嵌套。比如集合类型的每个元素只能是字符串,不能是一个集合或者散列表等。 散列类型适合存储对象:使用对象类别和ID构成建名,使用字段表示对象的属性,而字段值存储属性值。例如要存储ID为2的汽车对象,可以分别使用名为color、name和price的三个字段来存储该汽车的颜色、名称和价格。 [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100113_0_88475.jpg[/img] [b]1、基本命令[/b] 例如现在要存储ID为1的文章,分别有title、author、time、content 则键为post:1,字段分别为title、author、time、content,值分别为“the first post”、“me”、“2014-03-04”、“This is my first post.”,存储如下
redis 127.0.0.1:6379> hmset post:1 title "the first post" author "JoJo" time 2016/08/25 content "this is my first post"
OK
这里使用的是hmset命令,具体散列的基本赋值命令如下: [code]hset key field value[/code]   #例如hset post:2 title “second post” [code]hget key field[/code]             #例如hget post:2 title,获取id为2的post的title值 [code]hmset key field value [field value ...]  [/code]#这个同上,批量存值 [code]hmget key field [field ...] [/code]                     #批量取值,取得列表 例:
redis 127.0.0.1:6379> hmget post:1 time author
1) "2016/08/25"
2) "JoJo"
[code]hgetall key[/code]                  #取得key所对应的所有键值列表,这里给出个例子
redis 127.0.0.1:6379> hgetall post:1
1) "title"
2) "the first post"
3) "author"
4) "JoJo"
5) "time"
6) "2016/08/25"
7) "content"
8) "this is my first post"
[b] 2、判断是否存在[/b]
hexists key field
如果存在返回1,否则返回0(如果键不存在也返回0)。 [b]3、当字段不存在时赋值[/b]
hsetnx key field value
这个和[code]hset[/code]的区别就是如果字段存在,这个命令将不执行任何操作,但是这里有一个区别就是Redis提供的这些命令都是原子操作,不会产生数据不一致问题。 例:
redis 127.0.0.1:6379> hexists post:1 time
(integer) 1  //判断是存在time字段的
redis 127.0.0.1:6379> hsetnx post:1 time 2016/08/26
(integer) 0  //不存在的话,设置time,存在的话返回0,值不变,原始值
redis 127.0.0.1:6379> hget post:1 time
"2016/08/25"
redis 127.0.0.1:6379> hsetnx post:1 age 23
(integer) 1   //不存在age字段,返回1,并设置age字段
redis 127.0.0.1:6379> hget post:1 age
"23"
[b]4、增加数字[/b]
hincrby key field number
这里就和[code]incry[/code]命令类似了。 例:
redis 127.0.0.1:6379> hincrby post:1 age 2
(integer) 25
[b]5、删除字段[/b]
hdel key field [field ...]
删除字段,一个或多个,返回值是被删除字段的个数。 [b]6、其他命令[/b] [code]hkeys key[/code]    #获取字段名 [code]hvals key[/code]    #获取字段名 示例如下:
redis 127.0.0.1:6379> hkeys post:1
1) "title"
2) "author"
3) "time"
4) "content"
5) "age"
redis 127.0.0.1:6379> hvals post:1
1) "the first post"
2) "JoJo"
3) "2016/08/25"
4) "this is my first post"
5) "25"
最后还有一个就是获取字段数量的命令:
hlen key
返回字段的数量
redis 127.0.0.1:6379> hlen post:1
(integer) 5
[b]总结[/b] 以上就是Redis中散列类型常用命令的全部内容了,希望能对大家的学习或者工作带来一定的帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部