Redis实现排行榜(带二位小数点)
2021/9/17 19:08:53
本文主要是介绍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实现排行榜(带二位小数点)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-24Redis资料:新手入门快速指南
- 2024-12-24Redis资料:新手入门教程与实践指南
- 2024-12-24Redis资料:新手入门教程与实践指南
- 2024-12-07Redis高并发入门详解
- 2024-12-07Redis缓存入门:新手必读指南
- 2024-12-07Redis缓存入门:新手必读教程
- 2024-12-07Redis入门:新手必备的简单教程
- 2024-12-07Redis入门:新手必读的简单教程
- 2024-12-06Redis入门教程:从安装到基本操作
- 2024-12-06Redis缓存入门教程:轻松掌握缓存技巧