【C#与Redis】--实践案例--案例 3:使用 Redis 实现排行榜

2023-12-31 20:34:21

实现一个基本的排行榜系统通常涉及到对分数进行排序,而 Redis 的 Sorted Set 数据结构非常适合这种用途。以下是一个使用 StackExchange.Redis 库在 C# 中实现排行榜的简单案例:

  1. 安装 StackExchange.Redis 库:
Install-Package StackExchange.Redis
  1. 创建一个排行榜管理器类:
using StackExchange.Redis;
using System;

public class RedisLeaderboardManager
{
    private readonly Lazy<ConnectionMultiplexer> _lazyConnection;

    public RedisLeaderboardManager(string connectionString)
    {
        _lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(connectionString);
        });
    }

    private IDatabase GetDatabase()
    {
        return _lazyConnection.Value.GetDatabase();
    }

    public void AddScore(string leaderboardKey, string member, double score)
    {
        var database = GetDatabase();
        database.SortedSetAdd(leaderboardKey, member, score);
    }

    public double GetScore(string leaderboardKey, string member)
    {
        var database = GetDatabase();
        return database.SortedSetScore(leaderboardKey, member) ?? 0;
    }

    public long GetRank(string leaderboardKey, string member, bool highToLow = true)
    {
        var database = GetDatabase();
        long? rank;

        if (highToLow)
        {
            rank = database.SortedSetRank(leaderboardKey, member, Order.Descending);
        }
        else
        {
            rank = database.SortedSetRank(leaderboardKey, member);
        }

        return rank ?? -1; // -1 indicates that the member is not in the leaderboard
    }

    public SortedSetEntry[] GetTopPlayers(string leaderboardKey, long startRank, long stopRank, bool highToLow = true)
    {
        var database = GetDatabase();
        Order order = highToLow ? Order.Descending : Order.Ascending;
        return database.SortedSetRangeByRankWithScores(leaderboardKey, startRank, stopRank, order);
    }
}
  1. 在你的应用程序中使用排行榜:
class Program
{
    static void Main()
    {
        // 替换为你的 Redis 服务器连接字符串
        string redisConnectionString = "your_redis_connection_string";

        var leaderboardManager = new RedisLeaderboardManager(redisConnectionString);

        // 示例排行榜键
        string leaderboardKey = "game_leaderboard";

        // 模拟玩家分数
        leaderboardManager.AddScore(leaderboardKey, "player1", 1000);
        leaderboardManager.AddScore(leaderboardKey, "player2", 800);
        leaderboardManager.AddScore(leaderboardKey, "player3", 1200);

        // 获取玩家分数和排名
        double player1Score = leaderboardManager.GetScore(leaderboardKey, "player1");
        Console.WriteLine($"Player1 Score: {player1Score}");

        long player1Rank = leaderboardManager.GetRank(leaderboardKey, "player1");
        Console.WriteLine($"Player1 Rank: {player1Rank}");

        // 获取排行榜前两名玩家
        SortedSetEntry[] topPlayers = leaderboardManager.GetTopPlayers(leaderboardKey, 0, 1);
        foreach (var player in topPlayers)
        {
            Console.WriteLine($"{player.Element} - Score: {player.Score}");
        }

        Console.ReadLine();
    }
}

确保替换代码中的 your_redis_connection_string 为你的 Redis 服务器连接字符串。在这个案例中,我们使用 SortedSet 存储玩家分数,并通过不同的方法来获取分数、排名和排行榜的前几名玩家。你可以根据需要调整这些方法以满足具体业务需求。

文章来源:https://blog.csdn.net/gangzhucoll/article/details/135318821
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。