首页 > 其他 > 详细

Redis实现排行榜(带二位小数点)

时间:2021-09-21 01:01:57      阅读:9      评论:0      收藏:0      [点我收藏+]
public class UserRank {

    private String userId;

    private double score;
}


@RestController
@RequestMapping("rank")
public class RankController {

    @Autowired
    private RankService rankService;

    @GetMapping(value = "/add")
    public boolean add(String userId, double score){
        return rankService.add(userId, score);
    }

    @GetMapping(value = "/getRanks")
    public List<UserRank> getRanks(){
        return rankService.getRanks(0, 99);
    }

}


@Service
public class RankServiceImpl implements RankService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String SCORE = "score";
    public static final BigDecimal tailDecimal = new BigDecimal(String.valueOf(1000000000000000d));
    public static final BigDecimal milsDecimal = new BigDecimal(String.valueOf(9999999999999d));

    @Override
    public boolean add(String userId, double score) {
        BigDecimal dealScore  = new BigDecimal(String.valueOf(score));
        dealScore = dealScore.multiply(tailDecimal).add(milsDecimal).subtract(new BigDecimal(String.valueOf(System.currentTimeMillis())));
        return redisTemplate.opsForZSet().add(SCORE, userId, dealScore.doubleValue());
    }

    @Override
    public List<UserRank> getRanks(int start, int end) {
        Set<ZSetOperations.TypedTuple<String>> scoreSet = redisTemplate.opsForZSet().reverseRangeWithScores(SCORE, start, end);
        List<UserRank> userRanks = new ArrayList<>(scoreSet.size());
        for (ZSetOperations.TypedTuple s : scoreSet) {
            userRanks.add(new UserRank(s.getValue().toString(), new BigDecimal(String.valueOf(s.getScore())).divide(tailDecimal).setScale(2, BigDecimal.ROUND_DOWN).doubleValue()));
        }
        return userRanks;
    }

添加

http://localhost:8080/rank/add?userId=1111&score=2497444.91

查看前百排行

http://localhost:8080/rank/getRanks

如果还要其他的数据 可以根据userId查询

Redis实现排行榜(带二位小数点)

原文:https://www.cnblogs.com/weiapro/p/15303261.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!