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

(编辑:jimmy 日期: 2024/12/23 浏览:2)

我就废话不多说了,大家还是直接看代码吧~

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的前提下实现排行榜

项目地址https://github.com/liyiheng/zset

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。