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查询