Java中通過redis實現每日實時排行榜


 

通過redis中zset類型來實現每日排行榜還是比較容易的,但也有一些地方需要注意。

具體實現代碼如下:

1.設置數據

首先是要把需要的數據設置到redis中,注意分值前面的負號,由於zset特性是越小排到越前,所以分值需要加上負號才能到達分值越大排名越靠前的效果。

 1     /**
 2      * 設置排行榜信息
 3      *
 4      * @param anchorId
 5      * @param score
 6      * @param userId
 7      */
 8     public static void setRankInfoCache(UUID anchorId, Integer userId, Double score, Integer siteId) {
 9         getJedisClientProxy().zadd(SafeEncoder.encode(LiveAnchorContextCacheKey.getDayRewardCacheKey(anchorId, siteId)),
10                 -score, SafeEncoder.encode(String.valueOf(userId)));
11     }

 

2.獲取當日排行榜前十

 1     /**
 2      * 獲取當日排行榜前十信息緩存
 3      *
 4      * @param key
 5      * @return
 6      */
 7     public static List<LiveUserRankCache> getDayRankCache(String key) {
 8         List<LiveUserRankCache> userRankCacheList = new ArrayList<>();
 9         // TODO 默認取排行榜前十,可根據需求改成 TopN
10         Set<Tuple> tuples = getJedisClientProxy().zrangeWithScores(SafeEncoder.encode(key), 0, 9);
11         long rank = 1;
12         for (Tuple tuple : tuples) {
13             userRankCacheList.add(new LiveUserRankCache(rank, -tuple.getScore(), tuple.getElement()));
14         }
15         return userRankCacheList;
16     }

 

3.根據用戶ID獲取排行榜信息

 1     /**
 2      * 根據用戶ID獲取排行榜信息
 3      *
 4      * @param key
 5      * @param userId
 6      */
 7     public static LiveUserRankCache getRankInfoCache(String key, Integer userId) {
 8         Long rank = getJedisClientProxy().zrank(SafeEncoder.encode(key)
 9                 , SafeEncoder.encode(String.valueOf(userId)));
10         if (rank == null) {
11             // 沒有排行時,直接返回一個默認的
12             return new LiveUserRankCache(-1L, 0D, String.valueOf(userId));
13         }
14         Double zscore = getJedisClientProxy().zscore(SafeEncoder.encode(key)
15                 , SafeEncoder.encode(String.valueOf(userId)));
16         return new LiveUserRankCache(rank + 1, -zscore, String.valueOf(userId));
17     }

 完畢!僅供參考學習,轉載請在明顯位置注明出處,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM