VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • 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

出处:
https://www.cnblogs.com/weiapro/p/15303261.html

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


相关教程