ASP.NET Core 緩存Caching,.NET Core 中爲咱們提供了Caching 的組件。緩存
目前Caching 組件提供了三種存儲方式。學習
Memoryspa
Rediscode
SqlServerblog
學習在ASP.NET Core 中使用Caching。string
1.新建一個 ASP.NET Core 項目,選擇Web 應用程序,將身份驗證 改成 不進行身份驗證。it
2.添加引用io
Install-Package Microsoft.Extensions.Caching.Memory
3.使用class
在Startup.cs 中 ConfigureServicesservice
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); // Add framework services. services.AddMvc(); }
而後在
public class HomeController : Controller { private IMemoryCache _memoryCache; public HomeController(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public IActionResult Index() { string cacheKey = "key"; string result; if (!_memoryCache.TryGetValue(cacheKey, out result)) { result = $"LineZero{DateTime.Now}"; _memoryCache.Set(cacheKey, result); } ViewBag.Cache = result; return View(); } }
這裏是簡單使用,直接設置緩存。
咱們還能夠加上過時時間,以及移除緩存,還能夠在移除時回掉方法。
過時時間支持相對和絕對。
下面是詳細的各類用法。
public IActionResult Index() { string cacheKey = "key"; string result; if (!_memoryCache.TryGetValue(cacheKey, out result)) { result = $"LineZero{DateTime.Now}"; _memoryCache.Set(cacheKey, result); //設置相對過時時間2分鐘 _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(2))); //設置絕對過時時間2分鐘 _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(2))); //移除緩存 _memoryCache.Remove(cacheKey); //緩存優先級 (程序壓力大時,會根據優先級自動回收) _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.NeverRemove)); //緩存回調 10秒過時會回調 _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(10)) .RegisterPostEvictionCallback((key, value, reason, substate) => { Console.WriteLine($"鍵{key}值{value}改變,由於{reason}"); })); //緩存回調 根據Token過時 var cts = new CancellationTokenSource(); _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(cts.Token)) .RegisterPostEvictionCallback((key, value, reason, substate) => { Console.WriteLine($"鍵{key}值{value}改變,由於{reason}"); })); cts.Cancel(); } ViewBag.Cache = result; return View(); }
在ASP.NET Core MVC 中有一個 Distributed Cache 咱們能夠使用。
咱們直接在頁面上增長distributed-cache 標籤便可。
<distributed-cache name="mycache" expires-after="TimeSpan.FromSeconds(10)"> <p>緩存項10秒過時-LineZero</p> @DateTime.Now </distributed-cache> <distributed-cache name="mycachenew" expires-sliding="TimeSpan.FromSeconds(10)"> <p>緩存項有人訪問就不會過時,無人訪問10秒過時-LineZero</p> @DateTime.Now </distributed-cache>
這樣就能緩存標籤內的內容。
若是你以爲本文對你有幫助,請點擊「推薦」,謝謝。