实现的需求:排行榜前100名,分值相同的排名相同。这样从100万数据里面求前100名,可能有1000多个。
方法一:的思路就是把所有的分数存到redis的zset中,然后在每次添加的时候,记录前一百名的人数(同分时可能远大于100个人),然后从zset中取出改人数,即可求前一百名,同分并列的排行榜。
实现办法如下(配置Redis自行完成,下面代码拿取即可使用):
@RestController
public class SortBoardController {
@Autowired
private RedisTemplate redisTemplate;
/**
* 获取前100数据
*
* @return
*/
@GetMapping("/sort100")
public Set zsetTest() {
ZSetOperations<String, StudentEntity> zSetOperations = redisTemplate.opsForZSet();
TreeMap<Double, Integer> map = (TreeMap<Double, Integer>) redisTemplate.opsForValue().get("sortBoard");
System.out.println("=========================" + map);
Integer num = map.values().stream().collect(Collectors.summingInt(s -> s));
System.out.println("************************" + num);
Set<ZSetOperations.TypedTuple<StudentEntity>> set = zSetOperations.reverseRangeWithScores("student", 0, num - 1);
return set;
}
//模拟保存1000条数据
@GetMapping("/add")
public Set addTest() {
ZSetOperations<String, StudentEntity> zSetOperations = redisTemplate.opsForZSet();
for (int i = 0; i < 992; i++) {
Random ra = new Random();
final double d = Math.random();
DecimalFormat df = new DecimalFormat("#.00");
Double score = Double.valueOf(ra.nextInt(748) + 1) + Double.valueOf(df.format(d));
add(new StudentEntity(i, score, "onlyqi" + i, "38"), score);
}
for (int i = 992; i < 1000; i++) {
add(new StudentEntity(i, 749.50, "onlyqi" + i, "38"), 749.50);
}
Set<StudentEntity> set = zSetOperations.range("student", 0, -1);
return set;
}
/**
* 添加数据
*
* @param studentEntity
* @param score
*/
public void add(StudentEntity studentEntity, Double score) {
ZSetOperations<String, StudentEntity> zSetOperations = redisTemplate.opsForZSet();
zSetOperations.add("student", studentEntity, studentEntity.getScore());
addScore(score);
}
/**
* 计数器:记录最新的100名,并记录其个数
*
* @param score
*/
public void addScore(Double score) {
TreeMap<Double, Integer> map = (TreeMap<Double, Integer>) redisTemplate.opsForValue().get("sortBoard");
if (!Objects.isNull(map)) {
if (map.keySet().size() < 100) { //主要是刚开始,前一百名不存在,来即存
if (map.keySet().contains(score)) {
Integer num = map.get(score);
map.put(score, num++);
} else {
map.put(score, 1);
}
} else {//前一百名已经存在,来判断后存
if (map.keySet().contains(score)) {
Integer num = map.get(score);
map.put(score, num++);
} else if (score > map.firstKey()) {
map.remove(map.firstKey());
if (map.get(score) != null) {
Integer num = map.get(score);
map.put(score, num++);
} else {
map.put(score, 1);
}
}
}
} else {//也就第一次用的时候会走这里
map = new TreeMap<>();
map.put(score, 1);
}
redisTemplate.opsForValue().set("sortBoard", map);
}
方法二:redis中缓存TreeSet,该TreeSet中记录前100名的分数,每次添加数据的时候更TreeSet,在mysql中查大于TreeSet.first()就可以求出前一百名,同分并列的排行榜。
public static void getTop100(Integer[] score) {
TreeSet<Integer> top100 = new TreeSet();
for (int i = 0; i < score.length; i++) {
if (top100.size() < 100) {
top100.add(score[i]);
} else if ((Integer) top100.first() < score[i]&&!top100.contains(score[i])) {
Object obj = top100.first();
top100.remove(obj);
top100.add(score[i]);
}
}
}