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 with Go. 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.
Go1package main 2 3import ( 4 "context" 5 "fmt" 6 "github.com/redis/go-redis/v9" 7) 8 9var ctx = context.Background() 10 11func main() { 12 // Connect to Redis 13 client := redis.NewClient(&redis.Options{ 14 Addr: "localhost:6379", // redis port 15 DB: 0, // use default DB 16 }) 17 18 // Add user scores to the leaderboard 19 client.ZAdd(ctx, "leaderboard", redis.Z{Score: 100, Member: "user1"}) 20 client.ZAdd(ctx, "leaderboard", redis.Z{Score: 200, Member: "user2"}) 21 client.ZAdd(ctx, "leaderboard", redis.Z{Score: 150, Member: "user3"}) 22 23 // Retrieve top users 24 leaderboard, err := client.ZRevRangeWithScores(ctx, "leaderboard", 0, 2).Result() 25 if err != nil { 26 panic(err) 27 } 28 fmt.Println(leaderboard) 29 30 // Get user rank 31 rank, err := client.ZRevRank(ctx, "leaderboard", "user3").Result() 32 if err != nil { 33 panic(err) 34 } 35 36 // Get user score 37 score, err := client.ZScore(ctx, "leaderboard", "user3").Result() 38 if err != nil { 39 panic(err) 40 } 41 fmt.Println(rank, score) 42}
This example demonstrates how to add a score for a user, retrieve the top scores, and fetch a user’s rank and score using Go. You are familiar with the ZAdd
and ZRevRangeWithScores
commands from previous lessons. These commands are used to add scores and retrieve the leaderboard, respectively.
Now let's understand the ZRevRank
and ZScore
commands. The ZRevRank
command returns the rank of a member in a sorted set, with the highest score being ranked first. The ZScore
command retrieves the score of a member in a sorted set. They both receive 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.