在 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 接受用於查詢值的值,要快取的值以及一組 MemoryCacheEntryOptionsMemoryCacheEntryOptions 允許你指定絕對或滑動的基於時間的快取過期,快取優先順序,回撥和依賴關係。下面的一個樣本 -

_memoryCache.Set(cacheKey, greeting,
                new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));