golang-redis之sorted set类型操作详解
作者:代码界的小姑娘 时间:2024-02-02 05:19:20
1:安装redigo
go get github.com/garyburd/redigo/redis
2:引用redigo
import (
"github.com/garyburd/redigo/redis"
)
3:连接Redis
c, err := redis.Dial("tcp", "192.168.2.225:6379")
if err != nil {
fmt.Println("connect to redis err", err.Error())
return
}
defer c.Close()
4:命令
n,err := c.Do("zadd","key","score","member") //写
result,err := redis.Values(c.Do("zrange","key",0,-1))//读
5:sorted set简单操作
zadd(key, score1,member1,...scoreN,memberN) 向有序结合添加(更新)一个或多个成员
zcard(key):获取有序集合的成员
zcount(key,start,end):计算指定区间的成员数
zincrby(key,increment,member):成员member增加increment
zinterstore(dst,numkey,src1,src2..srcN):求交集,并将结果存储新的结合
zlexcount(key,start,end):计算字典区间成员数(分数都相同,按照字典排序)
zrange(key,start,end):获取索引区间的成员
zrangebylex (key,start,end):通过字典区间返回区间内有序集合成员
zrangebyscore(key,start,end):通过分数返回区间内的有序集合
zrank (key,member):返回有序结合的索引
zrem(key,members1...membersN):删除一个或多个成员
zremrangebylex(key,start,end):移除集合中给定字典区间的成员
zremrangebyrank(key,start,end):移除有序集合中给定的排名区间的所有成员
zremrangebyscore(key,start,end):移除给定分数区间的所有元素
zrevange(key,start,end):通过索引,分数由高到低,返回指定区域的元素
zrevrangebyscore(key,member):分数由高向低返回指定区间的成员数
zrevrank(key,member):分数从小到大,返回指定成员的排名
zscore(key,member):返回有序集中,成员的分数值
zunionstore(dst,numkeys,key1...keyN):返回给定的一个或多个集合的并集,并存储在新的集合中
zscan(key,cursor):迭代有序结合中的元素(包括元素成员和元素分值)
6:示例
6.1:zadd
_, err1 := c.Do("zadd", "curbike", 1, "mobike", 2, "xiaolan", 3, "ofo", 4, "xiaoming")
_, err2 := c.Do("zadd", "tmpdata", 0, "mobike", 0, "xiaolan", 0, "mysql", 0, "redis", 0, "mongo", 0, "xiaoming")
if err1 != nil || err2 != nil {
fmt.Println("zadd failed", err.Error())
}
6.2:zcard
num, err := c.Do("zcard", "curbike")
if err != nil {
fmt.Println("zcard failed", err.Error())
} else {
fmt.Printf("curbike's size is %s:", num)
}
6.3:zcount
num, err = c.Do("zcount", "curbike", 1, 3)
if err != nil {
fmt.Println("zcount failed ", err.Error())
} else {
fmt.Println("zcount num is :", num)
}
6.4:zincrby
num, err = c.Do("zincrby", "curbike", 3, "xiaolan")
fmt.Println(reflect.TypeOf(num))
if err != nil {
fmt.Println("zincrby failed", err.Error())
} else {
fmt.Println("after zincrby the :", num)
}
6.5:zinterstore
_, err = c.Do("zinterstore", "internewset", 2, "curbike", "tmpdata")
if err != nil {
fmt.Println("zinterstore failed", err.Error())
} else {
result, err := redis.Values(c.Do("zrange", "internewset", 0, 10))
if err != nil {
fmt.Println("interstore failed", err.Error())
} else {
fmt.Printf("interstore newset elsements are:")
for _, v := range result {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
}
6.6:zlexcount
num, err = c.Do("zlexcount", "tmpdata", "[mongo", "[xiaoming")
if err != nil {
fmt.Println("zlexcount failed", err.Error())
} else {
fmt.Println("zlexcount in tmpdata is :", num)
}
6.7:
res, err := redis.Values(c.Do("zrange", "curbike", 0, -1, "withscores"))
if err != nil {
fmt.Println("zrange in curbike failed", err.Error())
} else {
fmt.Printf("curbike's element are follow:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
6.8:zrangebylex
res, err = redis.Values(c.Do("zrangebylex", "tmpdata", "[mobike", "[redis"))
if err != nil {
fmt.Println("zrangebylex failed", err.Error())
} else {
fmt.Printf("zrangebylex in tmpdata:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
6.9:zrangebyscore
res, err = redis.Values(c.Do("zrangebyscore", "curbike", "(1", "(5"))
if err != nil {
fmt.Println("zrangebyscore failed", err.Error())
} else {
fmt.Printf("zrangebyscore's element:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
6.10:zrank
num, err = c.Do("zrank", "internewset", "xiaoming")
if err != nil {
fmt.Println("zrank failed ", err.Error())
} else {
fmt.Println("xiaoming's score is ", num)
}
6.11:
_, err = c.Do("zunionstore", "unewzset", 2, "curbike", "tmpdata")
if err != nil {
fmt.Println("zunionstore failed", err.Error())
} else {
res, err = redis.Values(c.Do("zrange", "unewzset", 0, 10))
if err != nil {
fmt.Println("zunionstore failed", err.Error())
} else {
fmt.Printf("union set are:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
}
6.12:zscore
ret, err := c.Do("zscore", "internewset", "xiaolan")
if err != nil {
fmt.Println("zscore failed", err.Error())
} else {
fmt.Printf("curbike 's xiaolan score is:%s\n", ret)
}
6.13:zrevrank
num, err = c.Do("zrevrank", "curbike", "ofo")
if err != nil {
fmt.Println("zrevrank failed", err.Error())
} else {
fmt.Println("ofo's zrevrank is :", num)
}
6.14:zrevrangebyscore
res, err = redis.Values(c.Do("zrevrangebyscore", "unewzset", 10, 2))
if err != nil {
fmt.Println("zrevrangebyscore failed", err.Error())
} else {
fmt.Printf("zrevrangebyscore are:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
6.15:zrevrange
res, err = redis.Values(c.Do("zrevrange", "unewzset", 0, 10))
err != nil {
fmt.Println("zrevrange failed:", err.Error())
} else {
fmt.Printf("zrevrange element:")
for _, v := range res {
fmt.Printf("%s ", v.([]byte))
}
fmt.Println()
}
6.16:zrem
num, err = c.Do("zrem", "unewzset", "mysql")
if err != nil {
fmt.Println("zrem failed", err.Error())
} else {
fmt.Println("zrem result is:", num)
}
6.17:zremrangebyrank
num, err = c.Do("zremrangebyrank", "unewzset", 1, 4)
if err != nil {
fmt.Println("zremrangebyrank failed", err.Error())
} else {
fmt.Println("zremrangebyrank result:", num)
}
6.18:zremrangebyscore
num, err = c.Do("zremrangebyscore", "curbike", 2, 5)
if err != nil {
fmt.Println("zremrangebyscore failed", err.Error())
} else {
fmt.Println("zremrangebyscore result:", num)
}
7:示例结果
完整代码路径
补充:go-redis使用之ZSet有序集合
ZSet(sorted set):有序不重复集合
ZSet的每个元素都会关联一个float64类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。
有序集合的成员是唯一的,但分数(score)却可以重复。
集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。 集合中最大的成员数为2的32次方 - 1
func GetRedisClient() *redis.Client {
return redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
}
// redisZsetTest Zset(sorted set有序不重复集合)
func redisZsetTest(cli *redis.Client){
lang := []redis.Z{
redis.Z{Score: 90.0, Member: "java"},
redis.Z{Score: 80.0, Member: "go"},
redis.Z{Score: 70.0, Member: "python"},
redis.Z{Score: 60.0, Member: "php"},
redis.Z{Score: 50.0, Member: "ruby"},
}
l1:= struct {
Score float64
Member interface{}
}{
40,
"javaScript",
}
//l2 :=redis.Z{
//Score: 30,
//Member: "Object-C",
//}
// 添加一个值
cli.ZAdd("lang",l1)
// 添加多个值
_,err:=cli.ZAdd("lang",lang...).Result()
if err != nil {
panic(err)
}
//升序:查询zset中指定区间的成员,-1代表取到最后
fmt.Println("ZRange:",cli.ZRange("lang",0,3).Val())//[javaScript ruby php python]
//降序:查询zset中指定区间的成员,-1代表取到最后
fmt.Println("ZRevRange:",cli.ZRevRange("lang",0,-1).Val())// [java go python php ruby javaScript]
// [Go javaScript ruby php python go java]
opt:=redis.ZRangeBy{
Min: "50",//最小分数
Max: "90",//最大分数
Offset: 2,//在满足条件的范围,从offset下标处开始取值
Count: 3,//查询结果集个数
}
//升序:根据opt条件查询Member成员
fmt.Println(cli.ZRangeByScore("lang",opt).Val())// [python go java]
//降序:根据opt条件查询Member成员
fmt.Println(cli.ZRevRangeByScore("lang",opt).Val())//[python php ruby]
//升序:根据下标范围返回的redis.Z结构体切片
fmt.Println(cli.ZRangeWithScores("lang",0,3).Val())//[{40 javaScript} {50 ruby} {60 php} {70 python}]
//降序:根据下标范围返回的redis.Z结构体切片
fmt.Println(cli.ZRevRangeWithScores("lang",0,-1).Val())//[{90 java} {80 go} {70 python} {60 php} {50 ruby} {40 javaScript}]
//升序:根据opt条件,返回的redis.Z结构体切片
fmt.Println(cli.ZRangeByScoreWithScores("lang",opt).Val())
//降序:根据opt条件,返回的redis.Z结构体切片
fmt.Println(cli.ZRevRangeByScoreWithScores("lang",opt).Val())
fmt.Println(cli.ZRangeByLex("lang",opt).Val())
fmt.Println(cli.ZRevRangeByLex("lang",opt).Val())
// 获取指定成员的score
f:=cli.ZScore("lang","go").Val()
fmt.Println(f)// 80
// 获取指定成员的下标
fmt.Println(cli.ZRank("lang","python").Val())//3
// 返回指定区间的成员个数
fmt.Println(cli.ZCount("lang","50","80").Val())//4
// 返回集合中成员的个数
fmt.Println(cli.ZCard("lang").Val())//6
// 根据成员名称,移除指定成员(可以多个): 0:失败 0<:成功
fmt.Println(cli.ZRem("lang","c++").Val())//0
fmt.Println(cli.ZRem("lang","javaScript","java").Val())//2
fmt.Println(cli.ZRange("lang",0,-1).Val())// [ruby php python go]
// 升序:根据下标区间移除指定成员
fmt.Println(cli.ZRemRangeByRank("lang",1,2).Val())//2:表示移除了两个
fmt.Println(cli.ZRangeWithScores("lang",0,-1).Val())// [{50 ruby} {80 go}]
// 升序:根据分数区间移除指定成员
fmt.Println(cli.ZRemRangeByScore("lang","70","90").Val())//1:表示移除了一个
fmt.Println(cli.ZRangeWithScores("lang",0,-1).Val())// [{50 ruby}]
}
func main() {
rdb := GetRedisClient()
defer rdb.Close()
pong := rdb.Ping().Val()
fmt.Printf("数据库连接状态:%v\n", pong) // 数据连接状态:PONG
redisZsetTest(rdb)
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/weixin_37696997/article/details/78634337
标签:golang-redis,sorted,set
0
投稿
猜你喜欢
python 实现学生信息管理系统的示例
2021-05-01 01:37:24
python中子类调用父类函数的方法示例
2023-12-30 14:17:03
python爬取各类文档方法归类汇总
2022-02-22 05:45:47
使用python 对验证码图片进行降噪处理
2022-01-27 23:02:16
sql2005开发版 没有任何功能可以安装
2024-01-16 20:48:18
python全栈知识点总结
2021-05-20 01:55:24
MySQL一些常用高级SQL语句详解
2024-01-29 02:45:22
商业价值与用户价值的平衡
2008-12-10 18:42:00
webpack vue 项目打包生成的文件,资源文件报404问题的修复方法(总结篇)
2024-04-27 16:10:21
asp如何限制重复订阅邮件或重复投票?
2010-06-09 18:48:00
Go 语言前缀树实现敏感词检测
2024-05-05 09:27:18
python 判断linux进程,并杀死进程的实现方法
2022-06-24 22:31:54
go mod 使用私有gitlab群组的解决方案
2024-05-22 10:29:28
Oracle 8x监控sysdba角色用户登陆情况
2024-01-19 08:56:43
pyhton学习与数据挖掘self原理及应用分析
2023-07-04 23:19:11
详解Vue中Computed与watch的用法与区别
2023-07-02 17:05:24
Python万字深入内存管理讲解
2021-06-30 15:49:33
CSS Shadow Practice
2009-04-01 18:37:00
Oracle 忘记密码的找回方法
2009-03-06 11:12:00
python儿童学游戏编程知识点总结
2022-10-23 04:32:42