Redis Demo系列之(四)排行榜

释放双眼,带上耳机,听听看~!

前言

通常游戏都会有统计装备评分的排行榜。这通常是使用Redis内的zset数据结构实现的。于此,同时还可以使用zremrangeByRank方法剔除超过比如1000的数据,以此来减少redis内的内存消耗。

本文相关代码,可在我的Github项目https://github.com/SeanYanxml/bigdata/tree/master/redis 目录下可以找到。
PS: (如果觉得项目不错,可以给我一个Star。)


Demo


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
1public class RankListDemo {
2
3    public static void main(String[] args) {
4        JedisPoolManager poolManager = new JedisPoolManager();
5        Jedis jedis = poolManager.getJedis();
6
7        // rank List
8        jedis.zadd("MoneyRankList", 1000000, "Jack Ma");// 马云
9        jedis.zadd("MoneyRankList", 800000, "Wang JianLin");//王建林
10        jedis.zadd("MoneyRankList", 900000, "Pony Ma");// 马化腾
11        jedis.zadd("MoneyRankList", 700000, "Liu Qiangdong");//刘强东
12        jedis.zadd("MoneyRankList", 600000, "Li Jiacheng");// 李嘉诚
13
14        // 获取排行榜前三名
15        System.out.println("Demo: Get Top 3:");
16        Set<String> top3MoneySet = jedis.zrevrange("MoneyRankList", 1, 3);// 财富榜前三名
17        int index = 0 ;
18        for(String name : top3MoneySet){
19            System.out.print(" || index: "+ ++index +" name: "+name + " money: "+ jedis.zscore("MoneyRankList", name));
20        }
21
22        // 获取某个成员的排名&score
23        System.out.println("\nDemo: Get One of the member:");
24        System.out.println(" || index: "+ jedis.zrank("MoneyRankList", "Wang JianLin") +" name: "+"Wang JianLin" + " money: "+ jedis.zscore("MoneyRankList", "Wang JianLin"));
25
26        // 每次保留 Top 3 超过Top3的全部删除
27        // 可以使用定时器 定时删除 或者加入后删除
28//       zremrangebyrank(key, min, max):删除名称为key的zset中rank >= min且rank <= max的所有元素
29//       zremrangebyscore(key, min, max) :删除名称为key的zset中score >= min且score <= max的所有元素
30        // 可以定期
31//      jedis.zremrangeByRank("MoneyRankList", 3, 100000000);
32        jedis.zremrangeByRank("MoneyRankList", 3, -1);
33
34        // 获取所有的排行榜
35        System.out.println("\nDemo: All members:");
36        Set<String> moneySet = jedis.zrevrange("MoneyRankList", 0, -1);// 财富榜前三名
37        index = 0 ;
38        for(String name : moneySet){
39            System.out.print(" || index: "+ ++index +" name: "+name + " money: "+ jedis.zscore("MoneyRankList", name));
40        }
41
42    }
43
44}
45

Reference

[1]. Redis: 使用Sorted Set 解决游戏中有关排行问题
[2]. redis 的sorted set做排行榜,怎么移除被挤到一定名次之后的数据项?

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索