. Net Core learning notes-MemoryCache,
. NET Core supports a variety of different caches, including MemoryCache, which indicates the cache stored in the Web server memory;
The cache in the memory stores any object. The distributed cache interface is limitedbyte[]
1: To use MemoryCache in. net core, you must first download the MemoryCache package.
On the Package Manager Console, enter the following command:Install-Package Microsoft. Extensions. Caching. Memory
Then we can see that the NuGet package has been downloaded"Microsoft. Extensions. Caching. Memory"
Use IMemoryCache: In-memory cache is a service referenced from an application using dependency injection. In Startup. cs
Public void ConfigureServices (IServiceCollection services) {// use dependency injection to reference services. AddMemoryCache (); services. AddMvc ();}
IMemoryCache requests an instance in the constructor:
// IMemoryCache requests the instance private IMemoryCache _ cache in the constructor; // private object CacheKeys; public HomeController (IMemoryCache memoryCache) {_ cache = memoryCache;} public IActionResult Index () {DateTime cacheEntry; string CacheKeys = "key"; // use TryGetValue to check whether the time is cached. if (! _ Cache. tryGetValue (CacheKeys, out cacheEntry) {// time is not cached, add a new entry cacheEntry = DateTime. now; // use Set to add it to the cache var cacheEntryOptions = new MemoryCacheEntryOptions () // during this period, the cache is maintained. If accessed, the time is reset. setSlidingExpiration (TimeSpan. fromSeconds (3); _ cache. set (cacheEntry, cacheEntry, cacheEntryOptions);} return View ("Index", cacheEntry );}
Display current time: cachedDateTime
The value is retained in the cache and there are requests within the timeout period (and the request is not evicted due to memory pressure)
@model DateTime?<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css"><link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css"><div>
CachedDateTime
The value is retained in the cache, and there are requests within the timeout period (and the request is not evicted due to memory pressure ). Displays the current time and earlier time retrieved from the cache: