Redis 06 哈希
阅读原文时间:2023年07月08日阅读:2

参考源

https://www.bilibili.com/video/BV1S54y1R7SB?spm_id_from=333.999.0.0

版本

本文章基于 Redis 6.2.6


哈希就是 key - map 的数据结构

应用场景:对象存储

赋值

Hset

127.0.0.1:6379> Hset hash f1 sail
(integer) 1

Hmset

127.0.0.1:6379> Hmset hash f2 sail2 f3 sail3
OK

Hsetnx

127.0.0.1:6379> Hkeys hash
1) "f1"
2) "f2"
3) "f3"
127.0.0.1:6379> Hsetnx hash f4 1 # f4 不存在,赋值成功
(integer) 1
127.0.0.1:6379> Hget hash f4
"1"
127.0.0.1:6379> Hsetnx hash f4 2 # f4 存在,赋值失败
(integer) 0
127.0.0.1:6379> Hget hash f4
"1"

Hincrby

127.0.0.1:6379> Hset hash f3 1
(integer) 1
127.0.0.1:6379> Hincrby hash f3 1 # 自增 1
(integer) 2
127.0.0.1:6379> Hincrby hash f3 -1 # 自减 1(哈希没有自减命令,用自增负数实现自减)
(integer) 1

取值

Hget

127.0.0.1:6379> Hget hash f1
"sail"

Hmget

127.0.0.1:6379> Hmget hash f2 f3
1) "sail2"
2) "sail3"

Hgetall

127.0.0.1:6379> Hgetall hash
1) "f1"
2) "sail"
3) "f2"
4) "sail2"
5) "f3"
6) "sail3"

Hkeys

127.0.0.1:6379> Hkeys hash
1) "f1"
2) "f2"

Hvals

127.0.0.1:6379> Hvals hash
1) "sail"
2) "sail2"

Hlen

127.0.0.1:6379> Hgetall hash
1) "f1"
2) "sail"
3) "f2"
4) "sail2"
127.0.0.1:6379> Hlen hash
(integer) 2

Hexists

127.0.0.1:6379> Hgetall hash
1) "f1"
2) "sail"
3) "f2"
4) "sail2"
127.0.0.1:6379> Hexists hash f1 # 存在返回 1
(integer) 1
127.0.0.1:6379> Hexists hash f3 # 不存在返回 0
(integer) 0

删除

Hdel

127.0.0.1:6379> Hdel hash f3
(integer) 1
127.0.0.1:6379> Hgetall hash
1) "f1"
2) "sail"
3) "f2"
4) "sail2"