【C#与Redis】--实践案例--案例 1:使用 Redis 实现缓存

在使用 Redis 实现缓存的案例中,我们可以使用 StackExchange.Redis 库,这是一个为 .NET 提供的 Redis 客户端库。以下是一个简单的使用 Redis 缓存的 C# 示例:

  1. 首先,你需要安装 StackExchange.Redis 库。可以通过 NuGet 包管理器控制台执行以下命令:
bash 复制代码
Install-Package StackExchange.Redis
  1. 然后,你可以创建一个简单的缓存管理器类,如下所示:
csharp 复制代码
using System;
using StackExchange.Redis;

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

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

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

    public T Get<T>(string key)
    {
        var database = GetDatabase();
        var value = database.StringGet(key);

        if (value.HasValue)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
        }

        return default(T);
    }

    public void Set<T>(string key, T value, TimeSpan? expiry = null)
    {
        var database = GetDatabase();
        var serializedValue = Newtonsoft.Json.JsonConvert.SerializeObject(value);

        if (expiry.HasValue)
        {
            database.StringSet(key, serializedValue, expiry);
        }
        else
        {
            database.StringSet(key, serializedValue);
        }
    }

    public bool Remove(string key)
    {
        var database = GetDatabase();
        return database.KeyDelete(key);
    }
}
  1. 然后,你可以在应用程序中使用这个缓存管理器:
csharp 复制代码
class Program
{
    static void Main()
    {
        // 替换为你的 Redis 服务器连接字符串
        string redisConnectionString = "your_redis_connection_string";

        var cacheManager = new RedisCacheManager(redisConnectionString);

        // 示例使用缓存
        string key = "example_key";
        string data = "example_data";

        // 从缓存获取数据
        string cachedData = cacheManager.Get<string>(key);

        if (cachedData == null)
        {
            // 如果缓存中没有数据,则从其他数据源获取数据
            Console.WriteLine("Data not found in cache. Fetching from another data source.");

            // 模拟从其他数据源获取数据
            cachedData = data;

            // 将数据放入缓存,设置过期时间为 1 小时
            cacheManager.Set(key, cachedData, TimeSpan.FromHours(1));
        }
        else
        {
            Console.WriteLine("Data found in cache.");
        }

        // 使用从缓存或其他数据源获取的数据
        Console.WriteLine($"Data: {cachedData}");

        // 清除缓存
        cacheManager.Remove(key);

        Console.ReadLine();
    }
}

请确保替换代码中的 your_redis_connection_string 为你的 Redis 服务器连接字符串。此外,你可以根据需要调整缓存键、数据获取逻辑和过期时间。

相关推荐
emplace_back18 分钟前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon1 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员2 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
开开心心_Every2 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
小码编匠4 小时前
C# 上位机开发怎么学?给自动化工程师的建议
后端·c#·.net
钢铁男儿5 小时前
C# 接口(什么是接口)
java·数据库·c#
用户8324951417326 小时前
Spring Boot 实现 Redis 多数据库切换(多数据源配置)
redis
小老鼠爱大米8 小时前
C# WPF - Prism 学习篇:搭建项目(一)
c#·wpf·prism