Redis 学习笔记Hash操作
Posted Adorable_Rocy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis 学习笔记Hash操作相关的知识,希望对你有一定的参考价值。
1.hset key filed val
127.0.0.1:6379> hset myhash k1 v1 # 设置键值对
(integer) 1
127.0.0.1:6379> hset myhash k2 v2
(integer) 1
127.0.0.1:6379>
2.hget key filed
127.0.0.1:6379> hget myhash k1 # 获取k1键的值
"v1"
127.0.0.1:6379> hget myhash k2
"v2"
127.0.0.1:6379>
3.hmet key …field …val| hmget …key
127.0.0.1:6379> hmset myhash k3 v3 k4 v4
OK
127.0.0.1:6379> hmget myhash k1 k2 k3 k4
1) "v1"
2) "v2"
3) "v3"
4) "v4"
127.0.0.1:6379>
4.hgetall key
127.0.0.1:6379> hgetall myhash
1) "k1"
2) "v1"
3) "k2"
4) "v2"
5) "k3"
6) "v3"
7) "k4"
8) "v4"
127.0.0.1:6379>
5.hdel key field
127.0.0.1:6379> hdel myhash k1 # 删除键为k1的字段,对应的值也会被删除
(integer) 1
127.0.0.1:6379> HGETALL myhash
1) "k2"
2) "v2"
3) "k3"
4) "v3"
5) "k4"
6) "v4"
127.0.0.1:6379>
6.hlen key
127.0.0.1:6379> HGETall myhash
1) "k2"
2) "v2"
3) "k3"
4) "v3"
5) "k4"
6) "v4"
127.0.0.1:6379> HLEN myhash # 获取总共有多少个字段(键)
(integer) 3
127.0.0.1:6379>
7.hexists key field
127.0.0.1:6379> hgetall myhash
1) "k2"
2) "v2"
3) "k3"
4) "v3"
5) "k4"
6) "v4"
127.0.0.1:6379> hexists myhash k2 # 判断是否存在键
(integer) 1
127.0.0.1:6379> hexists myhash k1
(integer) 0
127.0.0.1:6379>
8.hkeys key | hvals key
127.0.0.1:6379> hkeys myhash # 获得键中所有字段
1) "k2"
2) "k3"
3) "k4"
127.0.0.1:6379> hvals myhash # 获得键中所有值
1) "v2"
2) "v3"
3) "v4"
127.0.0.1:6379>
9.hincrby key field val
127.0.0.1:6379> hset myhash views 0
(integer) 1
127.0.0.1:6379> HINCRBY myhash views 5 # 指定增量(步数为5)
(integer) 5
127.0.0.1:6379> HINCRBY myhash views -3 # 完成自减操作
(integer) 2
127.0.0.1:6379> HINCRBY myhash views # 需要指定自增量,否则抛异常
(error) ERR wrong number of arguments for 'hincrby' command
127.0.0.1:6379> HINCRBY myhash views 1
(integer) 3
127.0.0.1:6379>
10.hsetnx key field val
127.0.0.1:6379> hkeys myhash
1) "k2"
2) "k3"
3) "k4"
4) "views"
5) "k1"
127.0.0.1:6379> hsetnx myhash k1 hello # 如果不存在才成功设置
(integer) 0
127.0.0.1:6379> hsetnx myhash k5 hello
(integer) 1
127.0.0.1:6379> HKEYS myhash # 已经存在的k1键便添加失败了
1) "k2"
2) "k3"
3) "k4"
4) "views"
5) "k1"
6) "k5"
127.0.0.1:6379> HVALS myhash # 查看键中所有的值
1) "v2"
2) "v3"
3) "v4"
4) "13"
5) "v1"
6) "hello"
127.0.0.1:6379>
11.对象
127.0.0.1:6379> hmset user:1 name zhangsan age 20 fans 0 # 生成对象,携带粉丝字段
OK
127.0.0.1:6379> hset user:1 name lisi # 修改字段的值.返回值为0,但是值已经被修改了
(integer) 0
127.0.0.1:6379> hget user:1 name
"lisi"
127.0.0.1:6379> HINCRBY user:1 fans 10 # 模拟fans增加操作
(integer) 10
127.0.0.1:6379> hget user:1 fans
"10"
127.0.0.1:6379>
以上是关于Redis 学习笔记Hash操作的主要内容,如果未能解决你的问题,请参考以下文章