ASP.NET Core 緩存Caching,.NET Core 中為我們提供了Caching 的組件。
目前Caching 組件提供了三種存儲方式。
Memory
Redis
SqlServer
學習在ASP.NET Core 中使用Caching。
Memory Caching
1.新建一個 ASP.NET Core 項目,選擇Web 應用程序,將身份驗證 改為 不進行身份驗證。
2.添加引用
Install-Package Microsoft.Extensions.Caching.Memory
3.使用
在Startup.cs 中 ConfigureServices
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(); }
Distributed Cache Tag Helper
在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>
這樣就能緩存標簽內的內容。
如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。
