.net Core學習筆記之MemoryCache

  .NET Core支持多種不一樣的緩存,其中包括MemoryCache,它表示存儲在Web服務器內存中的緩存; css

   內存中的緩存存儲任何對象; 分佈式緩存界面僅限於byte[]bootstrap

1:在.net core中使用MemoryCache首先要下載MemoryCache包緩存

     在程序包管理器控制檯輸入命令:Install-Package Microsoft.Extensions.Caching.Memory 服務器

     以後能夠看到已經下載好了NuGet包「Microsoft.Extensions.Caching.Memory分佈式

    使用IMemoryCache:內存中緩存是使用依賴注入從應用程序引用的服務,在Startup.cs中函數

 public void ConfigureServices(IServiceCollection services)
        {
            //使用依賴注入從應用程序引用服務
            services.AddMemoryCache();
            services.AddMvc();
        }

 

IMemoryCache在構造函數中請求實例:spa

 //IMemoryCache在構造函數中請求實例
        private IMemoryCache _cache;
       // private object CacheKeys;
       
        public HomeController(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }

        public IActionResult Index()
        {
            DateTime cacheEntry;
            string CacheKeys = "key";
            // 使用TryGetValue來檢測時間是否在緩存中
            if (!_cache.TryGetValue(CacheKeys, out cacheEntry))
            {
                //時間未被緩存,添加一個新條目
                cacheEntry = DateTime.Now;

                // 使用Set將其添加到緩存中
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // 在此期間保持高速緩存,若是被訪問,則從新設置時間
                    .SetSlidingExpiration(TimeSpan.FromSeconds(3));

                _cache.Set(cacheEntry, cacheEntry, cacheEntryOptions);
            }

            return View("Index", cacheEntry);
        }

顯示當前時間:緩存的DateTime值保留在高速緩存中,同時在超時期限內有請求(而且不因內存壓力而驅逐).net

@model DateTime?

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css">

<div>
    <h2>Actions</h2>
    <ul>
        <li><a asp-controller="Home" asp-action="CacheTryGetValueSet">TryGetValue and Set</a></li>
    </ul>
</div>

<h3>Current Time: @DateTime.Now.TimeOfDay.ToString()</h3>
<h3>Cached Time: @(Model == null ? "No cached entry found" : Model.Value.TimeOfDay.ToString())</h3>

緩存的DateTime值保留在高速緩存中,同時在超時期限內有請求(而且不因內存壓力而驅逐)。下圖顯示了從緩存中檢索的當前時間和較早的時間:code

相關文章
相關標籤/搜索