.NET 6简单使用MemoryCache缓存

依赖注入

builder.Services.AddMemoryCache();

我们依旧通过构造函数注入的方式获取MemoryCache的实例:

private readonly IMemoryCache _cache;
//还是通过构造函数的方法,获取
public MemoryCaching(IMemoryCache cache)
{
    _cache = cache;
}

.然后在方法里使用:

///键名,值,有效期
_cache.Set(cacheKey, cacheValue, TimeSpan.FromSeconds(cacheValid));
//通过键名获取值
_cache.Get(cacheKey)
//通过键名删除
_cache.Remove(cacheKey)

实际上MemoryCache缓存的使用还有很多讲究,比如缓存期限的处理问题,需要进一步研究。