背景
最近拿到多个排行榜相关的需求,按财富值,魅力值等单个或多个字段进行排序默认取前N条数据,考虑使用Redis进行排行榜实现,数据结构使用zset,本文对财富值和魅力值二个或多个字段排序的思路进行说明;需求背景
排行榜,按财富值和魅力值进行倒序排序,优先财富值排序,财富值相同则取魅力值数据需求设计
思路:这里使用Redis zset数据结构,主要考虑将score字段进行分段,例如,完整的score:1000020000,财富值:10000,魅力值:20000,分段去维护两个数据,整体作为score去查询 具体代码如下://key: channelId,频道ID //score: 分段排序:10000 20000 //member: userId,用户ID log.info("1.数据初始化"); RedisUtil.zAdd("channelId", "1000", 1000020000);//10000 20000 RedisUtil.zAdd("channelId", "2000", 1000020001);//10000 20001 RedisUtil.zAdd("channelId", "3000", 1000120000);//10001 20000 RedisUtil.zAdd("channelId", "4000", 1000120001);//10001 20001 log.info("2.数据分段处理"); Double score = RedisUtil.zScore("channelId", "4000"); //获取第一段排序 int scorePart1 = (int) ((score / 1000000000) * 10000); //获取第二段排序 int scorePart2 = (int) (score % 100000); log.info("member 10000,scorePart1:{},scorePart2:{}", scorePart1, scorePart2); log.info("3.数据查询结果"); Set<String> members = RedisUtil.zRange("channelId", 0, 4); log.info("members:{}", members); return BaseOutput.success();缓存数据
执行结果日志
024-12-27 14:39:20.550 [TID: N/A] INFO [abc123456789] [http-nio-9004-exec-1] c.l.i.u.controller.app.TestController -1.数据初始化 2024-12-27 14:39:20.770 [TID: N/A] INFO [abc123456789] [http-nio-9004-exec-1] c.l.i.u.controller.app.TestController -2.数据分段处理 2024-12-27 14:39:20.799 [TID: N/A] INFO [abc123456789] [http-nio-9004-exec-1] c.l.i.u.controller.app.TestController -member 10000,scorePart1:10001,scorePart2:20001 2024-12-27 14:39:20.799 [TID: N/A] INFO [abc123456789] [http-nio-9004-exec-1] c.l.i.u.controller.app.TestController -3.数据查询结果 2024-12-27 14:39:20.829 [TID: N/A] INFO [abc123456789] [http-nio-9004-exec-1] c.l.i.u.controller.app.TestController -members:[1000, 2000, 3000, 4000]
标签:10000,Zset,channelId,Redis,score,排序,RedisUtil,多字段 From: https://www.cnblogs.com/july-sunny/p/18635822