In-Memory Cache in ASP.NET Core
You can improve the performance of your application by using cache. Instead of generating the content, you can retrieve the content from the cache. You can use cache for rarely changing content. Instead of creating content, the cache will hold the content, so it will be available quickly.
ASP.NET Core support IMemoryCache, its cache storage in the memory of the webserver. Let's see how this works.
The following is a HomeController code. Here the IMemoryCache interface is implemented using dependency injection. You can see in the controller constructor IMemoryCache object has been passed.
In coding, the TryGetValue method checks if there is any cached content for the keyword ‘CacheDateKey’, which will provide content if there is any cached content in it. If there is no content in the cache. It will set the cache, i.e. the time for the cache. Also, the SetSlidingExpiration option is set in the example. This indicates how long the cache should be idle. If any user accesses the page within three seconds it will be active. If no one accesses the page for more than three seconds, the cache will expire.
HomeController.csusing Microsoft.Extensions.Caching.Memory; public class HomeController : Controller { private readonly IMemoryCache _cache; public HomeController(IMemoryCache memoryCache) { _cache = memoryCache; } public IActionResult Index() { DateTime cacheDateTime; if (!_cache.TryGetValue("CacheDateKey", out cacheDateTime)) { var cacheOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(3)); cacheDateTime = DateTime.Now; _cache.Set("CacheDateKey", cacheDateTime, cacheOptions); } return View(cacheDateTime); } }
IMemoryCache Interface Methods
CreateEntry(Object)
This method creates an entry in the cache. If the key has an entry, it will overwrite the cache entry. It will return ICacheEntry
using (var cacheEntry = _cache.CreateEntry("CacheDateKey")) { ... ... }
Remove(Object)
You can programmatically remove the contents of the cache using the Remove method. You can send the key as a parameter to remove the cached content.
TryGetValue(Object, Object)
TryGetValue will get the cache value based on the keyword. It returns the bool value. If there is cached content for the keyword it will return true otherwise false. Also, it has an out parameter. It will return a cached value, if there is no cached content it will return null.
DateTime cacheDateTime; if(!_cache.TryGetValue("CacheDateKey", out dt)) { // Set cache }
Memory Cache Entry Options
AbsoluteExpiration: This option allows you to set the exact date and time when the cached content will expire. The cache will expire on February 16, 2021, at 20:48:59 pm, according to the code below.
var cacheOptions = new MemoryCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(new DateTime(2021, 02, 16, 20, 48, 59)) };
AbsoluteExpirationRelativeToNow: It helps to set the time duration of the cache. For example, if your cache content needs to be active for 30 minutes you can set it up using this property. The cache expires after 30 minutes.
var cacheOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) };
ExpirationTokens: This expires the cache based on the IChangeToken instance.
PostEvictionCallbacks: It helps to get or set the callback fire after the cache entry has been removed from the cache.
Priority: This allows you to get and set cache priority. When prompted to clean the cache during memory pressure. It helps to prioritize the cache.
var cacheOptions = new MemoryCacheEntryOptions { Priority=CacheItemPriority.Normal, };
- NeverRemove:3
- High: 2
- Normal: 1
- Low:0
NeverRemove Priority never removes temporary storage. But the cache entry can be removed by the Remove method.
Size: This allows you to get and set the size of the cache.
SlidingExpiration:This helps to set the expiration time. This determines how long the cache should be idle. The cache will be inactive for 3 seconds from the code below. After that, the cached content will expire
var cacheOptions = new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromSeconds(3) };
I hope this helps you. Keep coding.
Comments
Post a Comment