C# 中的缓存:Redis、Memcached 及 .NET 内置解决方案
缓存是提升 C# 应用程序性能的关键工具之一。它能减少响应时间,降低数据库和外部 API 的负载。.NET 生态系统提供了多种方法:从内置的 MemoryCache 到基于 Redis 和 Memcached 的分布式解决方案。本文我们将分析每种方案、展示代码示例并提供选型建议。
1. 内置缓存:MemoryCache 与 IDistributedCache
.NET 平台提供了两种主要的缓存抽象机制:IMemoryCache(进程内)和 IDistributedCache(分布式)。
1.1 IMemoryCache
将数据存储在进程内存中。适用于无需多服务器同步的单线程或单体应用。配置简单,无需外部依赖。
// 添加到依赖注入 (Program.cs)builder.Services.AddMemoryCache();
// 在服务中使用public class WeatherService{ private readonly IMemoryCache _cache;
public WeatherService(IMemoryCache cache) { _cache = cache; }
public async Task<string> GetWeatherAsync(string city) { string cacheKey = $"weather_{city}"; if (_cache.TryGetValue(cacheKey, out string cachedData)) { return cachedData; }
// 模拟耗时请求 await Task.Delay(2000); string result = $"城市 {city} 天气:+25°C";
var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) .SetSlidingExpiration(TimeSpan.FromMinutes(2));
_cache.Set(cacheKey, result, options); return result; }}1.2 IDistributedCache
分布式缓存的抽象接口。允许在不更改业务逻辑的情况下轻松切换提供程序(Redis、SQL Server、NCache)。默认数据以 byte[] 形式存储。
// 注册 (Program.cs) - 使用 Redisbuilder.Services.AddStackExchangeRedisCache(options =>{ options.Configuration = "localhost:6379";});
// 使用public class ProductService{ private readonly IDistributedCache _cache;
public ProductService(IDistributedCache cache) { _cache = cache; }
public async Task<Product> GetProductAsync(int id) { string cacheKey = $"product_{id}"; var cachedBytes = await _cache.GetAsync(cacheKey);
if (cachedBytes != null) { return JsonSerializer.Deserialize<Product>(cachedBytes); }
// 数据库查询 var product = await GetProductFromDb(id);
var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromHours(1));
var serialized = JsonSerializer.SerializeToUtf8Bytes(product); await _cache.SetAsync(cacheKey, serialized, options);
return product; }}2. Redis:具备高级功能的分布式缓存
Redis 是 .NET 中最流行的缓存解决方案。它作为高性能内存存储运行,支持复杂数据结构(列表、哈希、集合)。
2.1 安装与配置
要将 Redis 接入 .NET,请使用 Microsoft.Extensions.Caching.StackExchangeRedis 包。
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis2.2 Redis 与 IDistributedCache 示例
除基础缓存外,Redis 还可实现:
- 用户会话 — 在请求间存储会话数据。
- 锁