我就废话不多说了,大家还是直接看代码吧~
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
补充:redis中zset的golang实现
zset
初衷是在不用redis的前提下实现排行榜
项目地址
installation
go get -u github.com/liyiheng/zset
usage
removed rwlock in the sortedset.
just implement it yourself if you need.
s := zset.new() // add data s.set(66, 1001, "test1") s.set(77, 1002, "test2") s.set(88, 1003, "test3") s.set(100, 1004, "liyiheng") s.set(99, 1005, "test4") s.set(44, 1006, "test5") // update data s.set(44, 1001, "test1") // get rank by id rank, score, extra := s.getrank(1004, false) // get data by rank id, score, extra := s.getdatabyrank(0, true) // get data by id dat, ok := s.getdata(1001) // delete data by id s.delete(1001)
benchmark
go test -test.bench=".*" benchmarksortedset_add-4 1000000 4121 ns/op benchmarksortedset_getrank-4 500000 3592 ns/op benchmarksortedset_getdatabyrank-4 2000000 667 ns/op pass ok zset 11.365s
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。