在使用 Redis 实现缓存的案例中,我们可以使用 StackExchange.Redis 库,这是一个为 .NET 提供的 Redis 客户端库。以下是一个简单的使用 Redis 缓存的 C# 示例:
- 首先,你需要安装 StackExchange.Redis 库。可以通过 NuGet 包管理器控制台执行以下命令:
Install-Package StackExchange.Redis
- 然后,你可以创建一个简单的缓存管理器类,如下所示:
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);}
}
- 然后,你可以在应用程序中使用这个缓存管理器:
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 服务器连接字符串。此外,你可以根据需要调整缓存键、数据获取逻辑和过期时间。