go操作redis的有序集合(zset)

robertkun發表於2017-12-06

go操作redis的有序集合(zset)

package main

import (
    "fmt"
    "github.com/garyburd/redigo/redis"
)

func main() {
    // 連線redis資料庫,指定資料庫的IP和埠
    conn, err := redis.Dial("tcp", "36.99.16.197:6379")
    if err != nil {
        fmt.Println("Connect to redis error", err)
        return
        } else {
        fmt.Println("Connect to redis ok.")
    }

    // 函式退出時關閉連線
    defer conn.Close()

    // 執行一個有序zset插入
    _, err = conn.Do("ZADD", "mykey", "INCR", 1, "robot1")
    if err != nil {
        fmt.Println("redis set failed:", err)
    }

    // 再執行一個有序zset插入
    _, err = conn.Do("ZADD", "mykey", "INCR", 1, "robot2")
    if err != nil {
        fmt.Println("redis set failed:", err)
    }

    // 讀取指定zset
    user_map, err := redis.StringMap(conn.Do("ZRANGE", "mykey", 0, 10, "withscores"))
    if err != nil {
        fmt.Println("redis get failed:", err)
    } else {
        fmt.Printf("Get mykey: %v \n", user_map)
    }

    for user := range user_map {
        fmt.Printf("user name: %v %v\n", user, user_map[user])
    }
}

輸出:
Connect to redis ok.
Get mykey: map[robot1:1 robot2:1]
user name: robot1 1
user name: robot2 1

相關文章