Redis在Springboot中的使用——Hash
数据类型详解
在讲解Redis中Hash的使用之前,大家需要知道Hash是怎么样的结构,方便在合适的场景中去使用。
这个我在之前的博客也有讲过,各位看官老爷可以移步到这篇博客
数据类型:散列表
操作命令
添加
127.0.0.1:6379> help hset
HSET key field value
summary: Set the string value of a hash field(设置散列字段的字符串的值)
since: 2.0.0
group: hash
127.0.0.1:6379> help hmset
HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values(批量设置散列字段的字符串的值)
since: 2.0.0
group: hash
如上一个是设置单个k-v,添加m之后就是批量设置k-v
127.0.0.1:6379> help HSETNX
HSETNX key field value
summary: Set the value of a hash field, only if the field does not exist(当且仅当散列值不存在时,设置散列值)
since: 2.0.0
group: hash
设置成功,返回 1 。
如果给定域已经存在且没有操作被执行,返回 0 。
获取
127.0.0.1:6379> help hget
HGET key field
summary: Get the value of a hash field(获取散列函数)
since: 2.0.0
group: hash
127.0.0.1:6379> help hmget
HMGET key field [field ...]
summary: Get the values of all the given hash fields(批量获取散列函数)
since: 2.0.0
group: hash
获取给定域中的值,当给定域不存在或者给定key不存在时,返回nil。
当获取多个的域的时候,按照顺序返回结果
127.0.0.1:6379> help hgetall
HGETALL key
summary: Get all the fields and values in a hash(获取散列值中所有的k-v)
since: 2.0.0
group: hash
127.0.0.1:6379[2]> help hkeys
HKEYS key
summary: Get all the fields in a hash(获取散列值中所有的k)
since: 2.0.0
group: hash
127.0.0.1:6379[2]> help hvals
HVALS key
summary: Get all the values in a hash(获取散列值中所有的v)
since: 2.0.0
group: hash
上述三个都是获取该散列值中的几种方法
127.0.0.1:6379[2]> help HLEN
HLEN key
summary: Get the number of fields in a hash(获取散列值中的k的数量)
since: 2.0.0
group: hash
修改
127.0.0.1:6379[2]> help HSET
HSET key field value
summary: Set the string value of a hash field(设置散列值字段的值)
since: 2.0.0
group: hash
127.0.0.1:6379[2]> help HMSET
HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values(批量设置)
since: 2.0.0
group: hash
127.0.0.1:6379[2]> help HSETNX
HSETNX key field value
summary: Set the value of a hash field, only if the field does not exist(存在就不在设置)
since: 2.0.0
group: hash
与上面添加类似,注意事项也与上述相同
删除
127.0.0.1:6379[2]> help HDEL
HDEL key field [field ...]
summary: Delete one or more hash fields(删除该散列值的字段)
since: 2.0.0
group: hash
其他操作
127.0.0.1:6379[2]> help HINCRBY
HINCRBY key field increment
summary: Increment the integer value of a hash field by the given number(将该hash字段的整数值以给定的数字递增)
since: 2.0.0
group: hash
增量也可以为负数,相当于对给定域进行减法操作。
- 如果 key 不存在,一个新的哈希表被创建并执行 HINCRBY 命令。
- 如果域 field 不存在,那么在执行命令前,域的值被初始化为 0 。
对一个储存字符串值的域 field 执行 HINCRBY 命令将造成一个错误。
使用
应用场景
购物车
用户个人详情
商品详情