最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Java和Redis實現(xiàn)排行榜功能實例代碼

 更新時間:2026年02月25日 09:51:06   作者:Zhu_S?W  
Redis是我們Java開發(fā)中,使用頻次非常高的一個nosql數(shù)據(jù)庫,數(shù)據(jù)以key-value鍵值對的形式存儲在內(nèi)存中,這篇文章主要介紹了基于Java和Redis實現(xiàn)排行榜功能的相關資料,需要的朋友可以參考下

引言

排行榜是現(xiàn)代應用程序中常見的功能,無論是游戲積分榜、銷售排行還是用戶活躍度統(tǒng)計,都需要高效的排序和查詢機制。Redis的有序集合(Sorted Set)數(shù)據(jù)結(jié)構(gòu)為實現(xiàn)排行榜提供了完美的解決方案,它能夠自動維護元素的排序,并支持高效的范圍查詢和排名操作。

Redis Sorted Set簡介

Redis的有序集合(Sorted Set)是一種特殊的數(shù)據(jù)結(jié)構(gòu),它具有以下特點:

  • 唯一性:集合中的每個元素都是唯一的

  • 有序性:每個元素都關聯(lián)一個分數(shù)(score),Redis根據(jù)分數(shù)自動排序

  • 高效性:插入、刪除、查找操作的時間復雜度都是O(log N)

  • 范圍查詢:支持按分數(shù)范圍或排名范圍查詢元素

環(huán)境準備

Maven依賴

首先,在項目的pom.xml中添加必要的依賴:

<dependencies>
    <!-- Jedis Redis客戶端 -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.1</version>
    </dependency>
    
    <!-- Spring Boot Redis Starter (可選) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.7.0</version>
    </dependency>
    
    <!-- JSON處理 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.14.2</version>
    </dependency>
</dependencies>

Redis配置

創(chuàng)建Redis連接配置類:

@Configuration
public class RedisConfig {
    
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName("localhost");
        factory.setPort(6379);
        factory.setDatabase(0);
        return factory;
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        return template;
    }
}

核心實現(xiàn)

1. 排行榜服務類

@Service
public class LeaderboardService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String LEADERBOARD_KEY = "game:leaderboard";
    
    /**
     * 更新用戶分數(shù)
     * @param userId 用戶ID
     * @param score 分數(shù)
     */
    public void updateScore(String userId, double score) {
        redisTemplate.opsForZSet().add(LEADERBOARD_KEY, userId, score);
    }
    
    /**
     * 增加用戶分數(shù)
     * @param userId 用戶ID
     * @param increment 增加的分數(shù)
     * @return 更新后的總分數(shù)
     */
    public Double incrementScore(String userId, double increment) {
        return redisTemplate.opsForZSet().incrementScore(LEADERBOARD_KEY, userId, increment);
    }
    
    /**
     * 獲取用戶當前分數(shù)
     * @param userId 用戶ID
     * @return 用戶分數(shù)
     */
    public Double getUserScore(String userId) {
        return redisTemplate.opsForZSet().score(LEADERBOARD_KEY, userId);
    }
    
    /**
     * 獲取用戶排名(從1開始)
     * @param userId 用戶ID
     * @return 用戶排名,如果用戶不存在返回null
     */
    public Long getUserRank(String userId) {
        Long rank = redisTemplate.opsForZSet().reverseRank(LEADERBOARD_KEY, userId);
        return rank != null ? rank + 1 : null;
    }
    
    /**
     * 獲取前N名排行榜
     * @param topN 獲取前幾名
     * @return 排行榜列表
     */
    public List<LeaderboardEntry> getTopN(int topN) {
        Set<ZSetOperations.TypedTuple<Object>> tuples = 
            redisTemplate.opsForZSet().reverseRangeWithScores(LEADERBOARD_KEY, 0, topN - 1);
        
        List<LeaderboardEntry> leaderboard = new ArrayList<>();
        int rank = 1;
        for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
            LeaderboardEntry entry = new LeaderboardEntry();
            entry.setUserId((String) tuple.getValue());
            entry.setScore(tuple.getScore());
            entry.setRank(rank++);
            leaderboard.add(entry);
        }
        return leaderboard;
    }
    
    /**
     * 獲取指定排名范圍的排行榜
     * @param startRank 起始排名(從1開始)
     * @param endRank 結(jié)束排名(包含)
     * @return 排行榜列表
     */
    public List<LeaderboardEntry> getRangeByRank(int startRank, int endRank) {
        Set<ZSetOperations.TypedTuple<Object>> tuples = 
            redisTemplate.opsForZSet().reverseRangeWithScores(
                LEADERBOARD_KEY, startRank - 1, endRank - 1);
        
        List<LeaderboardEntry> leaderboard = new ArrayList<>();
        int rank = startRank;
        for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
            LeaderboardEntry entry = new LeaderboardEntry();
            entry.setUserId((String) tuple.getValue());
            entry.setScore(tuple.getScore());
            entry.setRank(rank++);
            leaderboard.add(entry);
        }
        return leaderboard;
    }
    
    /**
     * 獲取指定分數(shù)范圍的用戶
     * @param minScore 最小分數(shù)
     * @param maxScore 最大分數(shù)
     * @return 用戶列表
     */
    public List<LeaderboardEntry> getRangeByScore(double minScore, double maxScore) {
        Set<ZSetOperations.TypedTuple<Object>> tuples = 
            redisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                LEADERBOARD_KEY, minScore, maxScore);
        
        List<LeaderboardEntry> result = new ArrayList<>();
        for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
            LeaderboardEntry entry = new LeaderboardEntry();
            entry.setUserId((String) tuple.getValue());
            entry.setScore(tuple.getScore());
            // 獲取具體排名
            Long rank = redisTemplate.opsForZSet().reverseRank(LEADERBOARD_KEY, tuple.getValue());
            entry.setRank(rank != null ? rank.intValue() + 1 : 0);
            result.add(entry);
        }
        return result;
    }
    
    /**
     * 獲取排行榜總?cè)藬?shù)
     * @return 總?cè)藬?shù)
     */
    public Long getTotalCount() {
        return redisTemplate.opsForZSet().zCard(LEADERBOARD_KEY);
    }
    
    /**
     * 刪除用戶
     * @param userId 用戶ID
     * @return 是否刪除成功
     */
    public Boolean removeUser(String userId) {
        Long removed = redisTemplate.opsForZSet().remove(LEADERBOARD_KEY, userId);
        return removed != null && removed > 0;
    }
}

2. 排行榜條目實體類

public class LeaderboardEntry {
    private String userId;
    private Double score;
    private Integer rank;
    
    // 構(gòu)造函數(shù)
    public LeaderboardEntry() {}
    
    public LeaderboardEntry(String userId, Double score, Integer rank) {
        this.userId = userId;
        this.score = score;
        this.rank = rank;
    }
    
    // Getter和Setter方法
    public String getUserId() { return userId; }
    public void setUserId(String userId) { this.userId = userId; }
    
    public Double getScore() { return score; }
    public void setScore(Double score) { this.score = score; }
    
    public Integer getRank() { return rank; }
    public void setRank(Integer rank) { this.rank = rank; }
    
    @Override
    public String toString() {
        return String.format("LeaderboardEntry{userId='%s', score=%.2f, rank=%d}", 
                           userId, score, rank);
    }
}

3. REST API控制器

@RestController
@RequestMapping("/api/leaderboard")
public class LeaderboardController {
    
    @Autowired
    private LeaderboardService leaderboardService;
    
    /**
     * 更新用戶分數(shù)
     */
    @PostMapping("/score")
    public ResponseEntity<String> updateScore(@RequestBody ScoreUpdateRequest request) {
        leaderboardService.updateScore(request.getUserId(), request.getScore());
        return ResponseEntity.ok("Score updated successfully");
    }
    
    /**
     * 增加用戶分數(shù)
     */
    @PostMapping("/increment")
    public ResponseEntity<Double> incrementScore(@RequestBody ScoreIncrementRequest request) {
        Double newScore = leaderboardService.incrementScore(request.getUserId(), request.getIncrement());
        return ResponseEntity.ok(newScore);
    }
    
    /**
     * 獲取用戶排名和分數(shù)
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<UserRankInfo> getUserInfo(@PathVariable String userId) {
        Double score = leaderboardService.getUserScore(userId);
        Long rank = leaderboardService.getUserRank(userId);
        
        if (score == null) {
            return ResponseEntity.notFound().build();
        }
        
        UserRankInfo info = new UserRankInfo(userId, score, rank);
        return ResponseEntity.ok(info);
    }
    
    /**
     * 獲取前N名排行榜
     */
    @GetMapping("/top/{n}")
    public ResponseEntity<List<LeaderboardEntry>> getTopN(@PathVariable int n) {
        List<LeaderboardEntry> leaderboard = leaderboardService.getTopN(n);
        return ResponseEntity.ok(leaderboard);
    }
    
    /**
     * 獲取指定排名范圍的排行榜
     */
    @GetMapping("/range")
    public ResponseEntity<List<LeaderboardEntry>> getRangeByRank(
            @RequestParam int startRank, 
            @RequestParam int endRank) {
        List<LeaderboardEntry> leaderboard = leaderboardService.getRangeByRank(startRank, endRank);
        return ResponseEntity.ok(leaderboard);
    }
    
    /**
     * 獲取排行榜統(tǒng)計信息
     */
    @GetMapping("/stats")
    public ResponseEntity<LeaderboardStats> getStats() {
        Long totalCount = leaderboardService.getTotalCount();
        List<LeaderboardEntry> topUsers = leaderboardService.getTopN(1);
        
        LeaderboardStats stats = new LeaderboardStats();
        stats.setTotalUsers(totalCount);
        if (!topUsers.isEmpty()) {
            stats.setTopUser(topUsers.get(0));
        }
        
        return ResponseEntity.ok(stats);
    }
}

高級功能

1. 多個排行榜管理

@Service
public class MultiLeaderboardService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String LEADERBOARD_PREFIX = "leaderboard:";
    
    /**
     * 獲取排行榜鍵名
     */
    private String getLeaderboardKey(String leaderboardType) {
        return LEADERBOARD_PREFIX + leaderboardType;
    }
    
    /**
     * 更新指定排行榜中用戶分數(shù)
     */
    public void updateScore(String leaderboardType, String userId, double score) {
        String key = getLeaderboardKey(leaderboardType);
        redisTemplate.opsForZSet().add(key, userId, score);
    }
    
    /**
     * 獲取用戶在多個排行榜中的排名
     */
    public Map<String, UserRankInfo> getUserRanksInMultipleBoards(String userId, List<String> leaderboardTypes) {
        Map<String, UserRankInfo> results = new HashMap<>();
        
        for (String type : leaderboardTypes) {
            String key = getLeaderboardKey(type);
            Double score = redisTemplate.opsForZSet().score(key, userId);
            Long rank = redisTemplate.opsForZSet().reverseRank(key, userId);
            
            if (score != null && rank != null) {
                results.put(type, new UserRankInfo(userId, score, rank + 1));
            }
        }
        
        return results;
    }
}

2. 時間窗口排行榜

@Service
public class TimeWindowLeaderboardService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 獲取日排行榜鍵名
     */
    private String getDailyLeaderboardKey() {
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return "leaderboard:daily:" + today;
    }
    
    /**
     * 獲取周排行榜鍵名
     */
    private String getWeeklyLeaderboardKey() {
        LocalDate now = LocalDate.now();
        int weekOfYear = now.get(WeekFields.ISO.weekOfYear());
        return String.format("leaderboard:weekly:%d-%02d", now.getYear(), weekOfYear);
    }
    
    /**
     * 更新日排行榜和總排行榜
     */
    public void updateDailyScore(String userId, double score) {
        String dailyKey = getDailyLeaderboardKey();
        String totalKey = "leaderboard:total";
        
        // 使用Redis事務確保一致性
        redisTemplate.execute(new SessionCallback<Object>() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForZSet().add(dailyKey, userId, score);
                operations.opsForZSet().incrementScore(totalKey, userId, score);
                return operations.exec();
            }
        });
        
        // 設置日排行榜過期時間(7天)
        redisTemplate.expire(dailyKey, 7, TimeUnit.DAYS);
    }
}

3. 排行榜緩存優(yōu)化

@Service
public class CachedLeaderboardService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String CACHE_KEY_PREFIX = "cache:leaderboard:";
    private static final int CACHE_EXPIRE_SECONDS = 300; // 5分鐘緩存
    
    /**
     * 獲取緩存的前N名排行榜
     */
    @Cacheable(value = "leaderboard", key = "'top:' + #topN")
    public List<LeaderboardEntry> getCachedTopN(int topN) {
        String cacheKey = CACHE_KEY_PREFIX + "top:" + topN;
        
        // 嘗試從緩存獲取
        List<LeaderboardEntry> cached = (List<LeaderboardEntry>) 
            redisTemplate.opsForValue().get(cacheKey);
        
        if (cached != null) {
            return cached;
        }
        
        // 緩存未命中,從排行榜獲取
        List<LeaderboardEntry> leaderboard = getTopN(topN);
        
        // 存入緩存
        redisTemplate.opsForValue().set(cacheKey, leaderboard, 
                                       CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
        
        return leaderboard;
    }
    
    /**
     * 清除相關緩存
     */
    public void clearLeaderboardCache() {
        Set<String> keys = redisTemplate.keys(CACHE_KEY_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}

性能優(yōu)化建議

1. 批量操作

對于大量的分數(shù)更新操作,建議使用批量處理:

public void batchUpdateScores(Map<String, Double> userScores) {
    redisTemplate.executePipelined(new SessionCallback<Object>() {
        @Override
        public Object execute(RedisOperations operations) throws DataAccessException {
            ZSetOperations<String, Object> zSetOps = operations.opsForZSet();
            userScores.forEach((userId, score) -> {
                zSetOps.add(LEADERBOARD_KEY, userId, score);
            });
            return null;
        }
    });
}

2. 連接池配置

優(yōu)化Redis連接池配置以提升性能:

@Configuration
public class RedisPoolConfig {
    
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(50);
        poolConfig.setMaxIdle(20);
        poolConfig.setMinIdle(10);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        
        JedisConnectionFactory factory = new JedisConnectionFactory(poolConfig);
        factory.setHostName("localhost");
        factory.setPort(6379);
        factory.setTimeout(3000);
        
        return factory;
    }
}

測試示例

@SpringBootTest
public class LeaderboardServiceTest {
    
    @Autowired
    private LeaderboardService leaderboardService;
    
    @Test
    public void testLeaderboard() {
        // 添加測試數(shù)據(jù)
        leaderboardService.updateScore("user1", 1000);
        leaderboardService.updateScore("user2", 1500);
        leaderboardService.updateScore("user3", 800);
        leaderboardService.updateScore("user4", 1200);
        
        // 測試獲取前3名
        List<LeaderboardEntry> top3 = leaderboardService.getTopN(3);
        assertEquals(3, top3.size());
        assertEquals("user2", top3.get(0).getUserId());
        assertEquals(1500.0, top3.get(0).getScore(), 0.01);
        
        // 測試用戶排名
        Long rank = leaderboardService.getUserRank("user2");
        assertEquals(Long.valueOf(1), rank);
        
        // 測試分數(shù)增加
        Double newScore = leaderboardService.incrementScore("user1", 600);
        assertEquals(1600.0, newScore, 0.01);
        
        // 驗證排名變化
        Long newRank = leaderboardService.getUserRank("user1");
        assertEquals(Long.valueOf(1), newRank);
    }
}

總結(jié)

使用Redis實現(xiàn)排行榜功能具有以下優(yōu)勢:

  • 高性能:Redis的內(nèi)存數(shù)據(jù)庫特性保證了快速的讀寫操作

  • 自動排序:Sorted Set自動維護元素排序,無需額外的排序操作

  • 豐富的操作:支持范圍查詢、排名查詢、分數(shù)更新等多種操作

  • 擴展性強:可以輕松實現(xiàn)多種類型的排行榜和時間窗口排行榜

通過合理的緩存策略和批量操作優(yōu)化,Redis排行榜系統(tǒng)可以輕松應對高并發(fā)場景,為用戶提供實時、準確的排名服務。在實際項目中,還可以根據(jù)具體需求添加更多功能,如排行榜歷史記錄、用戶分組排行等。

到此這篇關于基于Java和Redis實現(xiàn)排行榜功能的文章就介紹到這了,更多相關Java和Redis排行榜功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java用Cookie限制點贊次數(shù)(簡版)

    Java用Cookie限制點贊次數(shù)(簡版)

    最近做了一個項目,其中有項目需求是,要用cookie實現(xiàn)限制點贊次數(shù),特此整理,把實現(xiàn)代碼分享給大家供大家學習
    2016-02-02
  • 解決springboot導入失敗,yml未識別的問題

    解決springboot導入失敗,yml未識別的問題

    這篇文章主要介紹了解決springboot導入失敗,yml未識別的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • Java多線程之Callable接口的實現(xiàn)

    Java多線程之Callable接口的實現(xiàn)

    這篇文章主要介紹了Java多線程之Callable接口的實現(xiàn),Callable和Runnbale一樣代表著任務,區(qū)別在于Callable有返回值并且可以拋出異常。感興趣的小伙伴們可以參考一下
    2018-08-08
  • IntelliJ IDEA2025創(chuàng)建SpringBoot項目的實現(xiàn)步驟

    IntelliJ IDEA2025創(chuàng)建SpringBoot項目的實現(xiàn)步驟

    本文主要介紹了IntelliJ IDEA2025創(chuàng)建SpringBoot項目的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-07-07
  • 淺談Java中的高精度整數(shù)和高精度小數(shù)

    淺談Java中的高精度整數(shù)和高精度小數(shù)

    本篇文章主要介紹了淺談Java中的高精度整數(shù)和高精度小數(shù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Java使用MessageFormat應注意的問題

    Java使用MessageFormat應注意的問題

    這篇文章主要介紹了Java使用MessageFormat應注意的問題,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-06-06
  • Java反射機制的精髓講解

    Java反射機制的精髓講解

    今天小編就為大家分享一篇關于Java反射機制的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Spring Security認證機制源碼層探究

    Spring Security認證機制源碼層探究

    SpringSecurity是基于Filter實現(xiàn)認證和授權(quán),底層通過FilterChainProxy代理去調(diào)用各種Filter(Filter鏈),F(xiàn)ilter通過調(diào)用AuthenticationManager完成認證 ,通過調(diào)用AccessDecisionManager完成授權(quán)
    2023-03-03
  • java生成隨機字符串的兩種方法

    java生成隨機字符串的兩種方法

    這篇文章主要為大家詳細介紹了java生成隨機字符串的兩種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Java常見的四種負載均衡算法

    Java常見的四種負載均衡算法

    本文主要介紹了Java常見的四種負載均衡算法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-05-05

最新評論

营山县| 含山县| 新建县| 班戈县| 威信县| 芦山县| 乡宁县| 孝昌县| 静海县| 沅陵县| 那曲县| 黄陵县| 普陀区| 石景山区| 盐源县| 镇宁| 临潭县| 宣武区| 应城市| 永定县| 光泽县| 封开县| 威信县| 砀山县| 阿拉善左旗| 岳西县| 华池县| 泰宁县| 邮箱| 惠安县| 松潘县| 巍山| 民丰县| 乾安县| 阳高县| 林州市| 古蔺县| 北宁市| 永寿县| 牙克石市| 城步|