Redis-List-2

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

以下代码片段,涵盖对redis list的命令操作:

  1. RPUSH
  2. RPUSHX
  3. RPOP

Code

func ListTwo(c redis.Conn) {
    // Delete this list at first for test
    c.Do("DEL", "magpie")
    colorlog.Info("Command RPUSH")
    listLength, err := c.Do("RPUSH", "magpie", 1, 2, 3)
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    fmt.Println("After RPUSH, this list's length is:", listLength)
    values, _ := redis.Ints(c.Do("LRANGE", "magpie", 0, -1))
    fmt.Println("After RPUSH, list is:")
    for _, v := range values {
        fmt.Println(v)
    }
    colorlog.Info("Command RPUSHX")
    //  RPUSHX can only add a element once.
    listLength, err = c.Do("RPUSHX", "magpie", 4)
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    fmt.Println("After RPUSHX, this list's length is:", listLength)
    values, _ = redis.Ints(c.Do("LRANGE", "magpie", 0, -1))
    fmt.Println("After RPUSHX, list is:")
    for _, v := range values {
        fmt.Println(v)
    }
    //  RPUSHX will get error when add element to a key that is not a list
    c.Do("SET", "FakeNewListR", 1)
    _, err = c.Do("RPUSHX", "FakeNewListR", 1)
    if err != nil {
        colorlog.Error(err.Error())
    }
    //  RPUSHX will return 0 when add element to a key that doesn't exist
    listLength, err = c.Do("RPUSHX", "NullKeyFake", 1)
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    fmt.Println("After RPUSHX, this list's length is:", listLength)
    //  Command "RPOP"
    lastElement, err := c.Do("RPOP", "magpie")
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    fmt.Println("Last element is:", lastElement)
    values, _ = redis.Ints(c.Do("LRANGE", "magpie", 0, -1))
    fmt.Println("After RPOP, list is:")
    for _, v := range values {
        fmt.Println(v)
    }
    //  If list doesn't exist, will return nil
    lastElement, err = c.Do("RPOP", "NullKeyFake")
    if err != nil {
        colorlog.Error(err.Error())
        return
    }
    if lastElement == nil {
        fmt.Println("Last element is nil")
    }
}

Output

$ go run main.go
[INF]2020/04/10 15:55:04 Command RPUSH
After RPUSH, this list's length is: 3
After RPUSH, list is:
1
2
3
[INF]2020/04/10 15:55:04 Command RPUSHX
After RPUSHX, this list's length is: 4
After RPUSHX, list is:
1
2
3
4
[ERR]2020/04/10 15:55:04 WRONGTYPE Operation against a key holding the wrong kind of value
After RPUSHX, this list's length is: 0
Last element is: [52]
After RPOP, list is:
1
2
3
Last element is nil
上一篇下一篇

猜你喜欢

热点阅读