12.29 redis实现一个简单排行榜

项目描述:Redis实现的实时排行榜系统

本项目是一个基于 Spring Boot 和 Redis 的实时排行榜系统,利用 Redis 的有序集合(ZSet)数据结构高效地管理用户分数和排名。 用于Redis中Zset数据结构学习

Service

java 复制代码
package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class LeaderboardService {

    private static final String LEADERBOARD_KEY = "game:leaderboard";

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 增加或更新用户分数
    public void addOrUpdateScore(String userId, double score) {
        redisTemplate.opsForZSet().addIfAbsent(LEADERBOARD_KEY,userId,score);
    }


    // 获取用户排名(Redis 排名从 0 开始)
    public Long getUserRank(String userId) {
        Long l = redisTemplate.opsForZSet().reverseRank(LEADERBOARD_KEY, userId);
        if(l==null)return null;
        return l+1;
    }

    // 获取用户分数
    public Double getUserScore(String userId) {
        Double score = redisTemplate.opsForZSet().score(LEADERBOARD_KEY, userId);
        if(score==0)
            return null;
        return score;
    }

    // 获取排行榜前 N 名
    public Set<String> getTopUsers(int topN) {
        return   redisTemplate.opsForZSet().reverseRange(LEADERBOARD_KEY, 0, topN - 1);

    }
}

下面是control

java 复制代码
package org.example.control;

import org.example.service.LeaderboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/leaderboard")
public class LeaderboardController {

    @Autowired
    private LeaderboardService leaderboardService;

    // 增加或更新用户分数
    @PostMapping("/add")
    public String addScore(@RequestParam String userId, @RequestParam double score) {
        leaderboardService.addOrUpdateScore(userId, score);
        return "Score added/updated successfully!";
    }

    @PostMapping("/addBatch")
    public String addScoresBatch(@RequestBody List<Map<String, Object>> users) {
        for (Map<String, Object> user : users) {
            String userId = (String) user.get("userId");
            double score = Double.parseDouble(user.get("score").toString());
            leaderboardService.addOrUpdateScore(userId, score);
        }
        return "Batch scores added/updated successfully!";
    }
    // 获取用户排名和分数
    @GetMapping("/rank/{userId}")
    public Map<String, Object> getUserRank(@PathVariable String userId) {
        Long rank = leaderboardService.getUserRank(userId);
        Double score = leaderboardService.getUserScore(userId);

        return Map.of(
                "userId", userId,
                "rank", rank,
                "score", score
        );
    }

    // 获取排行榜前 N 名
    @GetMapping("/top/{topN}")
    public Map<String, Object> getTopUsers(@PathVariable int topN) {
        Set<String> topUsers = leaderboardService.getTopUsers(topN);
        
        // 获取每个用户的分数
        Map<String, Object> leaderboard = topUsers.stream()
                .collect(Collectors.toMap(
                        userId -> userId,
                        userId -> leaderboardService.getUserScore(userId)
                ));

        return Map.of("leaderboard", leaderboard);
    }
}
相关推荐
Zane19943 分钟前
HashMap 为什么要在长度16、容量必须是2的幂这些细节上较劲
java·后端
长谷深风11117 分钟前
为什么你的 Tool 总被模型选错?
java·大数据·ai·llm·ai agent·工具设计·agent设计
paopaokaka_luck1 小时前
基于springboot3+vue3的支教志愿者管理系统(AI问答、协同过滤算法、Echarts图形化分析)
spring boot·echarts
莫得感情 o1 小时前
并发 14 · 收官:虚拟线程与结构化并发
java·并发
聚美智数2 小时前
图片水印-图片剪裁-图片缩放API接口介绍
java·服务器·数据库
xierui1231232 小时前
AI Agent 隐私架构:本地化重点为什么是登录态与执行权限
java·人工智能·网络安全·架构
2601_963870182 小时前
【计算机毕业设计】基于Vue+Spring Boot的助农电商系统的设计与实现
spring boot·后端·课程设计
cfm_29143 小时前
Spring AI Tool 调用架构全解
java·人工智能·spring
sun༒3 小时前
Spring @Scheduled 定时任务详解:Cron表达式、执行顺序、优先级与并行调度
java·后端·spring
一次旅行3 小时前
DeepSeek‑V4‑Flash‑Vision‑Exp 小白入门实战|3种传图方式、完整可跑代码、避坑排障
java·前端·人工智能