.net Core学习笔记之MemoryCache

it2022-05-09  29

  .NET Core支持多种不同的缓存,其中包括MemoryCache,它表示存储在Web服务器内存中的缓存; 

   内存中的缓存存储任何对象; 分布式缓存界面仅限于byte[]

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在构造函数中请求实例:

//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值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)

@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值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)。下图显示了从缓存中检索的当前时间和较早的时间:

 

转载于:https://www.cnblogs.com/lcq529/p/8547956.html


最新回复(0)