C# 缓存:Redis、Memcached 及内置解决方案从入门到精通

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么缓存是 C# 应用程序的关键组件

\n\n

在现代 Web 开发中,应用程序性能直接影响用户体验和业务指标。页面加载每延迟一秒,可能导致 7% 的转化率损失。在 C# (.NET) 中实现缓存,不仅是“锦上添花”的功能,更是每位严肃开发者必备的工具。

\n\n

本文将深入探讨 .NET 生态系统中的三种主要缓存方案:Redis、Memcached 以及内置解决方案(MemoryCache)。您将了解何时使用哪种工具、如何正确配置缓存以及避免常见错误。本文适合从初级 C# 开发者到希望系统化知识的高级工程师。

\n\n

1. 内置缓存:MemoryCache 与 IDistributedCache

\n\n

.NET 平台为开发者提供了多种无需安装第三方服务的内置缓存机制。

\n\n

1.1 MemoryCache — 单服务器本地缓存

\n\n

IMemoryCache 是 C# 中最简单、最快速的缓存方式。数据存储在当前进程的内存中。非常适合单线程应用或运行在单台服务器上的应用。

\n\n
using Microsoft.Extensions.Caching.Memory;\n\npublic class ProductService\n{\n    private readonly IMemoryCache _cache;\n    \n    public ProductService(IMemoryCache cache)\n    {\n        _cache = cache;\n    }\n\n    public async Task<Product> GetProductAsync(int id)\n    {\n        string cacheKey = $"product_{id}";\n        \n        if (!_cache.TryGetValue(cacheKey, out Product product))\n        {\n            // 高开销操作(例如数据库查询)\n            product = await GetProductFromDatabaseAsync(id);\n            \n            var cacheOptions = new MemoryCacheEntryOptions()\n                .SetAbsoluteExpiration(TimeSpan.FromMinutes(30))\n                .SetSlidingExpiration(TimeSpan.FromMinutes(5))\n                .SetSize(1);\n            \n            _cache.Set(cacheKey, product, cacheOptions);\n        }\n        \n        return product;\n    }\n}
\n\n

MemoryCache 关键特性:

\n
    \n
  • 高速 — 直接从 RAM 读取数据
  • \n
  • 无需序列化 — 直接存储对象
  • \n
  • 局限性 — 不适用于服务器集群(每台服务器拥有独立缓存)
  • \n
  • 风险 — 应用程序重启时缓存完全清空
  • \n
\n\n

1.2 IDistributedCache — 分布式缓存抽象层

\n\n

IDistributedCache 接口提供了统一的 API 用于操作任何分布式缓存。您可以在 Redis、SQL Server 或 NCache 之间切换,而无需修改业务逻辑代码。

\n\n
using Microsoft.Extensions.Caching.Distributed;\nusing System.Text.Json;\n\npublic class WeatherService\n{\n    private readonly IDistributedCache _cache;\n    \n    public WeatherService(IDistributedCache cache)\n    {\n        _cache = cache;\n    }\n\n    public async Task<WeatherForecast> GetForecastAsync(string city)\n    {\n        string cacheKey = $"weather_{city}";\n        string cachedData = await _cache.GetStringAsync(cacheKey);\n        \n        if (cachedData != null)\n        {\n            return JsonSerializer.Deserialize<WeatherForecast>(cachedData);\n        }\n        \n        var forecast = await FetchFromApiAsync(city);\n        var serialized = JsonSerializer.Serialize(forecast);\n        \n        await _cache.SetStringAsync(cacheKey, serialized, new DistributedCacheEntryOptions\n        {\n            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15)\n        });\n        \n        return forecast;\n    }\n}
\n\n

2. R

博客

书籍推荐