在 ASP.NET Core 应用程序中使用 InMemory 缓存
要在 ASP.NET 应用程序中使用内存缓存,请将以下依赖项添加到 project.json
文件中:
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc2-final",
将缓存服务(从 Microsoft.Extensions.Caching.Memory)添加到 Startup 类中的 ConfigureServices 方法
services.AddMemoryCache();
要在我们的应用程序中向缓存添加项目,我们将使用 IMemoryCache
,它可以注入任何类(例如 Controller),如下所示。
private IMemoryCache _memoryCache;
public HomeController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
**** 如果存在, Get 将返回该值,否则返回 null
。
// try to get the cached item; null if not found
// greeting = _memoryCache.Get(cacheKey) as string;
// alternately, TryGet returns true if the cache entry was found
if(!_memoryCache.TryGetValue(cacheKey, out greeting))
使用 Set 方法写入缓存。Set 接受用于查找值的值,要缓存的值以及一组 MemoryCacheEntryOptions
。MemoryCacheEntryOptions
允许你指定绝对或滑动的基于时间的缓存过期,缓存优先级,回调和依赖关系。下面的一个样本 -
_memoryCache.Set(cacheKey, greeting,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));