前言
几乎在所有的应用程序中,缓存都是一个永恒的话题,恰当的使用缓存可以有效提高应用程序的性能;在某些业务场景下,使用缓存依赖会有很好的体验;在 Asp.Net Core 中,支持了多种缓存组件,这其中最基础也最易用的当属 IMemoryCache,该接口表示其存储依赖于托管程序服务器的内存,下面要介绍的内容就是基于 IMemoryCache 的缓存依赖。
1. IMemoryCache 的实现
Asp.Net Core 内部实现了一个继承自 IMemoryCache 接口的类 MemoryCache
这几乎已成惯例,一旦某个接口被列入 SDK 中,其必然包含了一个默认实现
1.1 使用 IMemoryCache
在 Asp.Net Core 中要使用 IMemoryCache 非常简单,只需要在 Startup 的 ConfigureServices 方法加入一句代码 services.AddMemoryCache() 即可
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); ... }1.2 在控制器中使用 IMemoryCache
[Route("api/[controller]")] [ApiController] public class HomeController : ControllerBase { private IMemoryCache cache; public HomeController(IMemoryCache cache) { this.cache = cache; } [HttpGet] public ActionResult<IEnumerable<string>> Get() { cache.Set("userId", "0001"); return new string[] { "value1", "value2" }; } [HttpGet("{id}")] public ActionResult<string> Get(int id) { return cache.Get<string>("userId"); } }上面的代码表示在 HomeController 控制器的构造方法中使用注入的方式获得了一个 IMemoryCache 对象,在 Get() 方法中增加了一条缓存记录 "userId=0001",然后在 Get(int id) 接口中提取该缓存记录
运行程序,分别调用 Get() 和 Get(int id) 接口,获得下面的输出信息
- 调用 Get() 接口

- 调用 Get(int id) 接口

这看起来非常容易,几乎不用什么思考,你就学会了在 Asp.Net Core 中使用缓存,容易使用,这非常重要,这也是一门语言广泛推广的根本态度
2. 应用缓存策略
IMemoryCache 还包含了一个带参数的构造方法,让我们可以对缓存进行灵活的配置,该配置由类 MemoryCacheOptions 决定
2.1 MemoryCacheOptions 配置,MemoryCacheOptions的配置项目不多,看下面的代码
public class MemoryCacheOptions : IOptions<MemoryCacheOptions> { public MemoryCacheOptions(); public ISystemClock Clock { get; set; } [Obsolete("This is obsolete and will be removed in a future version.")] public bool CompactOnMemoryPressure { get; set; } public TimeSpan ExpirationScanFrequency { get; set; } public long?
