Redis 实现一个简单的排行榜&计数器

Sorted Sets数据类型就像是set和hash的混合,与sets一样,Sorted Sets是唯一的,不重复的字符串组成。可以说Sorted Sets也是Sets的一种。

Sorted Sets是通过Skip List(跳跃表)和hash Table(哈希表)的双端口数据结构实现的,因此每次添加元素时,Redis都会执行O(log(N))操作。所以当我们要求排序的时候,Redis根本不需要做任何工作了,早已经全部排好序了。元素的分数可以随时更新。

依赖


      redis.clients
      jedis
      3.7.1

写一个Redis的接口类

public interface RedisClient {
   //新增
   Long zAdd(String key,String value,Double score);
   //获取排行
   Set zrevrange(String key, int start, int stop);
   //增分
  Double zincrby(String key, double increment, String value);
  // 获取分数
  Double score(String key,String value);
  // 计数器
  Double incrByFloat(String key, double increment);
}

接着写一个Redis 实现类

public class RedisAloneClient implements RedisClient {

    @Autowired(required = false)
    private JedisPool jedisPool;
   
   @Override
    public Long zAdd(String key, String value, Double score) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zadd(key,score,value);
        } finally {
            closeJedis(jedis);
        }
    }

    @Override
    public Set zrevrange(String key, int start, int stop) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zrevrange(key,start,stop);
        } finally {
            closeJedis(jedis);
        }
    }

 @Override
    public Double zincrby(String key, double increment, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zincrby(key,increment,value);
        } finally {
            closeJedis(jedis);
        }
    }

   @Override
    public Double incrByFloat(String key, double increment){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.incrByFloat(key,increment);
        } finally {
            closeJedis(jedis);
        }
    }

     @Override
    public Double score(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zscore(key,value);
        } finally {
            closeJedis(jedis);
        }
    }

    private void closeJedis(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }
  
}

在写Controller类之前先写入参和出参的类
1、新增和更新入参类

@Data
public class RankingParam {
    //用户Id
    private String userId;
   //分数
    private Double score;
}

2、获取排行榜的入参类

@Data
public class RankingTopParam {
   //开始排名
    private Integer start;
   //结束排名
    private Integer end;
}

3、返回排行榜出参类

@Data
public class RankingTopResult {
   //用户Id
    private String userId;
   //分数
    private Double score;
}

接着写Controller类

@RestController
@RequestMapping("/rankingList")
public class RankingListController {

    @Resource
    RankingListServiceFacade rankingListServiceFacade;

    @PostMapping("/add")
    public Result addRankingList(@RequestBody RankingParam param){

        return rankingListServiceFacade.addRankingList(param);
    }

    @PostMapping("/updateScore")
    public Result updateScore(@RequestBody RankingParam param){

        return rankingListServiceFacade.updateStore(param);
    }

    @PostMapping("/getRankingListTop")
    public Result> getRankingListTop(@RequestBody RankingTopParam param){

        return rankingListServiceFacade.getRankingListTop(param);
    }
}

接着写Facade类

public interface RankingListServiceFacade {
    /**
     * 新增排行榜
     * @param param
     * @return
     */
    Result addRankingList(RankingParam param);

     /**
     * 新增分数
     * @param param
     * @return
     */
    Result updateStore(RankingParam param);

    /**
     * 获取排行榜
     * @param param
     * @return
     */
    Result> getRankingListTop(RankingTopParam param);

}

impl类

@Service(value = "rankingListFacade")
public class RankingListServiceFacadeImpl implements RankingListServiceFacade {

    @Resource
    private RedisClient redisClient;

    static final String RANKING_LIST_KEY = "SCORE_RANK";


    @Override
    public Result addRankingList(RankingParam param){
        redisClient.zAdd(RANKING_LIST_KEY,param.getUserId(),param.getScore());

        return Result.success("新增成功");
    }

    @Override
    public Result updateStore(RankingParam param){
        redisClient.zincrby(RANKING_LIST_KEY,param.getScore(),param.getUserId());
        return Result.success("加分成功");
    }

    @Override
    public Result> getRankingListTop(RankingTopParam param){
        Set stringSet = redisClient.zrevrange(RANKING_LIST_KEY,param.getStart(),param.getEnd());
        List rankingTopResults = new ArrayList<>();
        for(String userId:stringSet){
            Double score = redisClient.score(RANKING_LIST_KEY,userId);
            RankingTopResult rankingTopResult = new RankingTopResult();
            rankingTopResult.setUserId(userId);
            rankingTopResult.setScore(score);
            rankingTopResults.add(rankingTopResult);
        }
        return Result.success(rankingTopResults);
    }
}

测试,新增和更新分数都调用add


截屏2022-05-23 13.58.24.png

获取排行旁


截屏2022-05-23 13.59.21.png

只需要做新增更新的操作后,直接就可以获取排行榜了,当然这只是个简单的demo,如果要实现复杂的排行榜自己修改。

思考:
1、比如要返回用户名和头像怎么办
2、如果获取前10名+用户自己的排名怎么实现
3、排名数据如何同步到数据库

扩展

如果实现计数器该怎么实现?

@Service(value = "redisCounterServiceFacade")
public class RedisCounterServiceFacadeImpl implements RedisCounterServiceFacade {
    @Resource
    private RedisClient redisClient;

    @Override
    public Result addCounter(CounterParam param) {
        redisClient.incrByFloat(param.getUserId(),param.getScore());
        return Result.success("");
    }

    @Override
    public Result updateCounter(CounterParam param){
        redisClient.incrByFloat(param.getUserId(),param.getScore());
        return Result.success("");
    }

    @Override
    public Result getCounter(CounterParam param){
        String score = redisClient.get(param.getUserId());
        CounterResult counterResult = new CounterResult();
        counterResult.setUserId(param.getUserId());
        counterResult.setScore(Double.parseDouble(score));
        return Result.success(counterResult);
    }
}

你可能感兴趣的:(Redis 实现一个简单的排行榜&计数器)