HLEN
- 如果hash表存在且有字段,则返回字段的数量
- 如果hash表没有字段,或者key不存在,则返回0
值得一提的是,当hash表没有字段时,
exists
命令返回的是0。也就相当于这个hash表已经不存在了。所以在上面的第二点中,均是返回0。
Command
$ redis-cli.exe -h 127.0.0.1 -p 6379
127.0.0.1:6379> hset snake name kobe
(integer) 1
127.0.0.1:6379> hlen snake
(integer) 1
127.0.0.1:6379> hdel snake name
(integer) 1
127.0.0.1:6379> hlen snake
(integer) 0
127.0.0.1:6379> exists fakeKey
(integer) 0
127.0.0.1:6379> hlen fakeKey
(integer) 0
Code
func Hlen(c redis.Conn) {
defer c.Do("DEL", "snake")
// If hash table is existing and has field(s), will return the number of fields.
c.Do("HSET", "snake", "name", "kobe")
lengthOfTable, err := c.Do("HLEN", "snake")
if err != nil {
colorlog.Error(err.Error())
return
}
fmt.Println("If hash table is existing, will return the number of fields:", lengthOfTable)
// if no fields in hash table, it will return 0. But if key doesn't exist, it still returns 0.
// Make hash table null at first for test.
c.Do("HDEL", "snake", "name")
lengthOfTable, err = c.Do("HLEN", "snake")
if err != nil {
colorlog.Error(err.Error())
}
fmt.Println("If hash table doesn't have any fields, will return:", lengthOfTable)
// If key doesn't exist, will return 0.
isExist, _ := c.Do("EXISTS", "fakeKey")
if isExist == 1 {
c.Do("DEL", "fakeKey")
}
lengthOfTable, err = c.Do("HLEN", "fakeKey")
if err != nil {
colorlog.Error(err.Error())
}
fmt.Println("If key doesn't exist, will return:", lengthOfTable)
}
Ouput
$ go run main.go
If hash table is existing, will return the number of fields: 1
If hash table doesn't have any fields, will return: 0
If key doesn't exist, will return: 0
网友评论