코딩하는 오징어

Spring에서 Redis ZSET구조 이용하기 본문

Framework/Spring

Spring에서 Redis ZSET구조 이용하기

코딩하는 오징어 2018. 2. 26. 17:00
반응형

Redis의 ZSET구조를 이용하여 LEADER BOARD 구현하기


@Repository
public class LeaderBoardRedisRepository {

    public static final String KEY = "leaderBoard";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private ZSetOperations<String, String> zSetOps;

    @PostConstruct
    public void init() {
        zSetOps = redisTemplate.opsForZSet();
    }

    public List<String> getPlayersRankOfRange(int startIndex, int endIndex) {
        Set<String> rankReverseSet = zSetOps.reverseRange(KEY, startIndex, endIndex);
        Iterator<String> iter = rankReverseSet.iterator();
        List<String> list = new ArrayList<>(rankReverseSet.size());

        while (iter.hasNext()) {
            list.add(iter.next());
        }

        return list;
    }

    public PlayerRankModel getOnePlayerRank(String nickname) {
        Long playerRank = zSetOps.reverseRank(KEY, nickname);

        if (playerRank == null) {
            throw new NotFoundException("Please check nickname");
        }

        PlayerRankModel playerRankModel = new PlayerRankModel();
        playerRankModel.setNickname(nickname);
        playerRankModel.setRank(playerRank.longValue() + 1);
        playerRankModel.setScore(zSetOps.score(KEY, nickname));

        return playerRankModel;
    }

    public void updateLeaderBoard(String winner, double winnerScore, String loser, double loserScore) {
        zSetOps.add(KEY, winner, winnerScore);
        zSetOps.add(KEY, loser, loserScore);
    }
}



반응형
Comments