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

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

阅读更多
版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/78733660
文章标签: go redis zset
个人分类: golang
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭