1.在pom文件导入:
java
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2.yml文件配置
java
redis:
port: 6379
host: localhost
database: 5
3.代码:
java
import java.util.Set;
@RestController
@RequestMapping("/leaderboard")
public class testController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 增加玩家分数
* @param player
* @param score
*/
@PostMapping("/add")
public void addPlayerScore(String player, double score) {
stringRedisTemplate.opsForZSet().add("playerRanking", player, score);
}
/**
* 获取前N名玩家排名
* @param topN
* @return
*/
@GetMapping("/top")
public Set<ZSetOperations.TypedTuple<String>> getPlayerRanking(int topN) {
return stringRedisTemplate.opsForZSet().reverseRangeWithScores("playerRanking", 0, topN - 1);
}
/**
* 获取玩家排名
* @param player
* @return
*/
@GetMapping("/rank")
public Long getPlayerRank(String player) {
return stringRedisTemplate.opsForZSet().reverseRank("playerRanking", player) + 1;
}
/**
* 对应的加分操作
*/
@GetMapping("/increment")
public void incrementScore(String player,double socre){
stringRedisTemplate.opsForZSet().incrementScore("playerRanking",player,socre);
}
}
4.插入数据:
java
@SpringBootTest
public class test {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void batchAddPlayers() {
Random random = new Random();
for (int i = 1; i <= 20; i++) {
String player = "Player" + i;
double score = random.nextDouble() * 100;
stringRedisTemplate.opsForZSet().incrementScore("playerRanking",player,score);
}
}
}
5.结果:
![请添加图片描述](https://i-blog.csdnimg.cn/direct/ad2fa7880deb4f69a6754979711db20f.png