Redis(三)哈希类型(hash)的使用

Redis哈希类型(hash)的使用

哈希表示字段和值之间的映射关系、类似对象和对象的属性之间的关系适合使用哈希类型

1
2
3
4
5
// 一次性设置和获取多个哈希属性键值
127.0.0.1:6379> hmset "hqd8080" "phone" "18111111111" "address" "shanghai china"
127.0.0.1:6379> hmget "hqd8080" "phone" "address"
1) "18111111111"
2) "shanghai china"
1
2
// 获取哈希的一个属性hget
127.0.0.1:6379> hget hqd8080 address // "shanghai china"
1
2
// 测试哈希中是否存在某个字段、属性,hexists
127.0.0.1:6379> hexists hqd8080 "phone" // (integer) 1
1
2
3
4
5
6
// 获取哈希中的所有字段 hgetall
127.0.0.1:6379> hgetall hqd8080
1) "phone"
2) "18111111111"
3) "address"
4) "shanghai china"
1
2
3
4
5
// 删除哈希中的摸个字段,hdel
127.0.0.1:6379> hdel hqd8080 "phone"
127.0.0.1:6379> hgetall hqd8080
1) "address"
2) "shanghai china"
1
2
// 仅当哈希字段不存在时才创建,避免hmset的覆盖字段行为
127.0.0.1:6379> hsetnx "hqd8080" "phone" "11111111111"
1
2
3
4
5
6
7
// 哈希字段非常多建议使用hscan,是一种指针迭代器,不会造成服务器阻塞,适合非常大的哈希
127.0.0.1:6379> hscan hqd8080 0 match "*a*"
1) "0" // 服务器返回的新游标,用来进行一次新的迭代,0代表哈希遍历完成
2) 1) "address"
2) "shanghai china"

127.0.0.1:6379> hscan hqd8080 新游标 match "*a*"