RScoredSortedSet 完成游戏内的排行榜

RankManager.java

package org.example.testRank;

import org.redisson.Redisson;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.ScoredEntry;
import org.redisson.config.Config;

import java.util.Collection;

public class RankManager {
    /*** 排行榜类型*/
    public static final String RANK_KEY = "RANK_KEY";

    private RScoredSortedSet rank;

    public static RankManager instance = new RankManager();

    public static RankManager inst() {
        return instance;
    }

    public void init() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379");

        RedissonClient redisson = Redisson.create(config);

        // 使用String类型编解码器
        rank = redisson.getScoredSortedSet(RANK_KEY, new StringCodec());
    }

    public void addOrUpdateRank(String rid, int score) {
        rank.add(score, rid);

        // 只保留前2名数据
        if (rank.size() > 2) {
            rank.pollFirst();
        }
    }

    public Collection> getRanks() {
        return rank.entryRangeReversed(0, -1);
    }
}

Main.java

package org.example.testRank;

import org.redisson.client.protocol.ScoredEntry;

import java.util.Collection;

public class Main {
    public static void main(String[] args) {
        RankManager rankManager = RankManager.inst();
        rankManager.init();

        rankManager.addOrUpdateRank("1001", 100);
        rankManager.addOrUpdateRank("1002", 80);
        rankManager.addOrUpdateRank("1003", 90);
        rankManager.addOrUpdateRank("1005", 60);

        // 模拟此人分数提高了
        rankManager.addOrUpdateRank("1002", 200);
        rankManager.addOrUpdateRank("1005", 666);


        Collection> ranks = rankManager.getRanks();
        for (ScoredEntry entry : ranks) {
            String value = entry.getValue();
            Double score = entry.getScore();
            System.out.println("rid=" + value + " score=" + score);
        }

    }
}

/*
rid=1005 score=666.0
rid=1002 score=200.0
 */

总结:虽然Redisson中支持泛型,但是排行榜中人家已经指定了必须通过Score进行排名,因此不可能让我们重写一个JavaBean的方式重新制定排序规则。

你可能感兴趣的:(#,redis,游戏)