When developing projects, cache is often used to cache some data according to their business needs, or cache the content of database queries to reduce the pressure on the database.
Commonly used memory caches: System.Runtime.Caching / MemoryCache and Microsoft.Extensions.Caching.Memory
Microsoft has 2 solutions, 2 different NuGet packages for caching, both are great, according to Microsoft's recommendation, prefer to use Microsoft.Extensions.Caching.Memory because it integrates better with Asp .NET core. It can be easily injected into Asp .NET Core's dependency injection mechanism.
This article uses Microsoft.Extensions.Caching.Memory to cache data, which is abbreviated as MSCache, and Microsoft introduces:The hyperlink login is visible.
Note: Microsoft.Extensions.Caching.Memory is thread-safe
What can MSCache do?
- Absolute expired support
- Sliding expiration support (specify a time, TimeSpan, postponed if there is a cached time within the specified time, otherwise it will expire)
- Expired callback
- Custom expiration
MemoryCacheEntryOptions cache settings
- AbsoluteExpirationAbsolute expiration time, if null, the condition is invalid
- AbsoluteExpirationRelativeToNowThe absolute expiration time relative to the current time (using TimeSpan) is null condition invalid
- SlidingExpirationSlide the expiration time
- ExpirationTokensAvailable to customize cache expiration
- PostEvictionCallbacksCache invalidation callbacks
- PriorityCache item priority (the order in which the cache is absolutely cleared when the cache is full)
- SizeRepresents the size of the cached data, which is generally null in the in-memory cache
Get started with MSCache
Project ASP.NET Core MVC nuget command installation:
When using, make simple packages.
Interface:
Implementation:
Dependency injection configuration singleton
Tests use MSCache
Write data using relative expiration and sliding expiration and perform a read test with the code as follows.
Controller Code:
Write cached data:
Read cached data:
Access:The hyperlink login is visible.After setting the relative expiration and sliding expiration, access: https://localhost:44370/Home/Get Get the cached data as follows:
Within 30 seconds, I visited the link to read the cache multiple times and found that the absolute expiration completely expired after 30 seconds, but I could still read it after sliding the expiration, as shown in the figure below:
(End)
|