ZSOCRE

2020-04-17  本文已影响0人  NotFoundW

ZSOCRE

  1. 如果有序集合和成员都存在,则返回成员的分数
  2. 如果有序集合存在,但成员不存在,则返回nil
  3. 如果key不存在,则返回nil

Command

$ redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> zadd animal 1 cat 2 dog
(integer) 2
127.0.0.1:6379> zscore animal dog
"2"
127.0.0.1:6379> zscore animal fish
(nil)
127.0.0.1:6379> exists fakeSortedSetKey
(integer) 0
127.0.0.1:6379> zscore fakeSortedSetKey fakeMember
(nil)

Code

func zscore(c redis.Conn) {
    defer c.Do("DEL", "animal")
    c.Do("ZADD", "animal", 1, "cat", 2, "dog")
    //  1. If sorted set and specified member both are existing, returns score of member.
    score, err := redis.Int(c.Do("ZSCORE", "animal", "dog"))
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    fmt.Println("If sorted set and specified member both are existing, the score of member:", score)
    //  2. If sorted set is existing but specified member doesn't, returns nil.
    score, err = redis.Int(c.Do("ZSCORE", "animal", "fish"))
    if err == redis.ErrNil {
        fmt.Println("If sorted set is existing but specified member doesn't, returns nil:")
        colorlog.Error(err.Error())
        fmt.Println("In golang, nil result should be", score, "for int type here.")
    }
    //  3. If key doesn't exist, returns nil.
    isExist, _ := c.Do("EXISTS", "fakeSortedSetKey")
    if isExist == 1 {
        c.Do("DEL", "fakeSortedSetKey")
    }
    score, err = redis.Int(c.Do("ZSCORE", "fakeSortedSetKey", "fakeMember"))
    if err == redis.ErrNil {
        fmt.Println("If key doesn't exist, returns nil:")
        colorlog.Error(err.Error())
        fmt.Println("In golang, nil result should be", score, "for int type here.")
    }
}

Output

$ go run main.go 
If sorted set and specified member both are existing, the score of member: 2
If sorted set is existing but specified member doesn't, returns nil:
[ERR]2020/04/17 14:20:51 redigo: nil returned  
In golang, nil result should be 0 for int type here.
If key doesn't exist, returns nil:
[ERR]2020/04/17 14:20:51 redigo: nil returned  
In golang, nil result should be 0 for int type here.
上一篇下一篇

猜你喜欢

热点阅读