C# 缓存:Redis、Memcached 及内置解决方案——完全指南
在现代 Web 开发中,应用程序性能是成功的关键因素之一。缓存可以显著降低数据库负载并加快系统响应速度。在 C# (.NET) 生态系统中,开发者可以使用三种主要方法:内置内存缓存 (IMemoryCache)、分布式解决方案 (IDistributedCache) 以及外部缓存服务器,例如 Redis 和 Memcached。在本文中,我们将从理论到实际代码示例逐一剖析每种方法。
1. .NET 内置缓存:IMemoryCache
内置缓存是临时存储数据最简单、最快速的方式。在 ASP.NET Core 中,它通过 IMemoryCache 接口实现。数据存储在单个进程的 RAM 中,从而确保最低延迟。
何时使用:
- 无需在多个服务器之间同步数据。
- 缓存数据量较小。
- 无需配置外部服务即可获得最高性能。
实现示例:
using Microsoft.Extensions.Caching.Memory;
public class WeatherService{ private readonly IMemoryCache _cache;
public WeatherService(IMemoryCache cache) { _cache = cache; }
public async Task<WeatherData> GetWeatherAsync(string city) { string cacheKey = $"weather_{city}";
if (!_cache.TryGetValue(cacheKey, out WeatherData data)) { // 缓存中没有数据——从外部源加载 data = await FetchWeatherFromApi(city);
// 缓存配置:生存时间 5 分钟 var cacheOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
_cache.Set(cacheKey, data, cacheOptions); }
return data; }
private async Task<WeatherData> FetchWeatherFromApi(string city) { // 模拟外部 API 调用 await Task.Delay(1000); return new WeatherData { City = city, Temperature = 22.5 }; }}
public class WeatherData{ public string City { get; set; } public double Temperature { get; set; }}关键方法:TryGetValue、Set、Remove。请务必记住,IMemoryCache 不适用于微服务架构。
2. 分布式缓存:IDistributedCache 及其提供程序
对于运行在多个服务器上的应用程序,需要使用分布式缓存。在 .NET 中,它通过 IDistributedCache 接口进行抽象。这使得无需更改业务逻辑即可轻松切换提供程序(Redis、SQL Server、NCache)。
主要方法:
GetAsync / SetAsync— 用于处理字节数据。GetStringAsync / SetStringAsync— 用于字符串数据。RefreshAsync— 重置滑动过期计时器。RemoveAsync— 删除条目。
Redis 示例:
// 在 Program.cs 中注册提供程序builder.Services.AddStackExchangeRedisCache(options =>{ options.Configuration = "localhost:6379"; options.InstanceName = "SampleApp";});
// 在服务中使用public class ProductService{ private readonly IDistributedCache _cache;
public ProductService(IDistributedCache cache) { _cache = cache; }
public async Task<Product> GetProductAsync(int id) { string cacheKey = $"product_{id}"; string cachedData = await _cache.GetStringAsync(cacheKey);
if