Welcome to the next exciting part of our Redis-based backend system project. In this unit, we will focus on building leaderboard functionality using Redis's sorted sets. Building a leaderboard is a popular use case for many applications, such as games and competitive platforms. You’ve got a good handle on managing user data from previous lessons, so let’s build on that foundation.
Let's briefly review what we’ll focus on in this unit. Our main tasks will be:
- Adding user scores to a leaderboard: We will store user scores using Redis sorted sets.
- Retrieving the leaderboard: We will fetch and display the top users and their scores.
- Getting a user's rank and score: We will retrieve the ranking and score of a specific user.
Below are some key parts of the code you will be working with to perform these tasks.
Java1import io.lettuce.core.RedisClient; 2import io.lettuce.core.api.sync.RedisCommands; 3 4public class LeaderboardExample { 5 public static void main(String[] args) { 6 // Connect to Redis 7 RedisClient redisClient = RedisClient.create("redis://localhost:6379/"); 8 RedisCommands<String, String> commands = redisClient.connect().sync(); 9 10 commands.zadd("leaderboard", 100, "user1"); 11 commands.zadd("leaderboard", 200, "user2"); 12 commands.zadd("leaderboard", 150, "user3"); 13 14 var leaderboard = commands.zrevrangeWithScores("leaderboard", 0, 2); 15 leaderboard.forEach(entry -> System.out.println(entry.getValue() + ": " + entry.getScore())); 16 17 Long rank = commands.zrevrank("leaderboard", "user3"); 18 Double score = commands.zscore("leaderboard", "user3"); 19 System.out.println("Rank: " + rank + ", Score: " + score); 20 21 redisClient.shutdown(); 22 } 23}
This example demonstrates how to add a score for a user, retrieve the top scores, and fetch a user’s rank and score. You have been introduced to the zadd
and zrevrangeWithScores
commands in previous lessons. These methods are used to add scores and retrieve the leaderboard, respectively.
Now let's understand the zrevrank
and zscore
commands. The zrevrank
method returns the rank of a member in a sorted set, with the highest score being ranked first. The zscore
method retrieves the score of a member in a sorted set. They both take the set name and the member as parameters.
Now that you have an overview, let's dive into the practice section to start implementing these components. Your hands-on work will strengthen your understanding, setting you up for success in creating robust backend features.