C# (.NET) 中的缓存:Redis 及其他加速应用程序的工具
缓存是提升 C# (.NET) 应用程序性能和可扩展性的最有效方法之一。在本文中,我们将详细探讨内置的缓存机制、流行的 Redis 操作库以及替代方案。您将了解如何根据任务正确选择工具并避免常见错误。
.NET 中的内置缓存机制
.NET 平台提供了多种现成的缓存解决方案,无需安装第三方依赖即可适用于大多数场景。
1. MemoryCache (System.Runtime.Caching)
进程内内存缓存。适用于单线程应用程序或低负载场景。数据存储在 RAM 中,并在资源不足时自动清除。
using System.Runtime.Caching;
public class MemoryCacheService{ private readonly MemoryCache _cache = MemoryCache.Default;
public T GetOrSet<T>(string key, Func<T> factory, int expirationMinutes = 5) { var cached = _cache.Get(key); if (cached != null) return (T)cached;
var result = factory(); var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(expirationMinutes) }; _cache.Set(key, result, policy); return result; }}2. IDistributedCache (Microsoft.Extensions.Caching)
分布式缓存的抽象层。允许轻松切换 Redis、SQL Server、NCache 等不同提供程序。推荐用于微服务和云应用程序。
using Microsoft.Extensions.Caching.Distributed;using System.Text.Json;
public class DistributedCacheService{ private readonly IDistributedCache _cache;
public DistributedCacheService(IDistributedCache cache) { _cache = cache; }
public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> factory, int expirationMinutes = 10) { var cached = await _cache.GetStringAsync(key); if (cached != null) return JsonSerializer.Deserialize<T>(cached);
var result = await factory(); var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) }; await _cache.SetStringAsync(key, JsonSerializer.Serialize(result), options); return result; }}Redis:分布式缓存之王
Redis 是一个高性能的内存数据存储,支持字符串、列表、哈希、集合等多种数据结构。对于 .NET,主要的库是 StackExchange.Redis。
安装和配置 StackExchange.Redis
通过 NuGet 安装包:
dotnet add package StackExchange.Redis连接和基本操作示例:
using StackExchange.Redis;
public class RedisCacheService{ private readonly ConnectionMultiplexer _redis; private readonly IDatabase _db;
public RedisCacheService(string connectionString) { _redis = ConnectionMultiplexer.Connect(connectionString); _db = _redis.GetDatabase(); }
public async Task SetAsync(string key, string value, int expirationMinutes = 5) { await _db.StringSetAsync(key, value, TimeSpan.FromMinutes(expirationMinutes)); }
public async Task<string> GetAsync(string key) { return await _db.StringGetAsync(key); }}Redis 高级功能
- Pub/Sub — 服务间通知
- Sorted Sets — 排行榜和排名