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>
这样就能缓存标签内的内容。
若是你以为本文对你有帮助,请点击“推荐”,谢谢。