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

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实现排行榜(带二位小数点)

上一篇:Android Studio - Unable to access Android SDK add-on list - Mac


下一篇:欧拉计划001--3或5的倍数