How to use memory cache in ASP. Net core

Time:2021-6-9

Asp.net core is a lightweight and modular framework, which is often used to build high-performance and modern web framework on windows, Linux and MacOS. Unlike asp.net in the past, there is no built-in cache object in asp.net core, but you can implement the following three kinds of cache through the extension of nuget

  • in-memory caching
  • distributed caching
  • response caching

In this article, we’ll see how to flood the immutable data into memory to achieve the high performance of asp.net core application, and then I’ll illustrate these concepts with some examples.

How to enable in memory cache

If you want toin-memory cacheTo integrate into asp.net core, you need to inject it into the servicecollection container, as shown in the following code:


public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddMemoryCache();
}

After integration, let’s take a look at the unified interface of cache: imemorycache. The code is as follows:


public interface IMemoryCache : IDisposable
{
    bool TryGetValue(object key, out object value);
    ICacheEntry CreateEntry(object key);
    void Remove(object key);
}

How to use it in controller? You can use the constructor of controller to implement injection, as shown in the following code:


    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private IMemoryCache cache;

        public HomeController(ILogger<HomeController> logger, IMemoryCache cache)
        {
           _logger = logger;
        }
    }

So far, the configuration of in memory caching has been completed. Now we can consider how to read and write from the cache.

Read and write of cache

Using imemorycache interfaceSet<T>()Write data to the cache, please note thisSet<T>()Method receives two parameters. The first parameter is the name of the cache, and the second parameter is the content you want to cache, as shown in the following code:


        public IActionResult Index()
        {
            cache.Set("IDGKey", DateTime.Now.ToString());
            return View();
        }

To extract content from the cache, you need to use the interface of imemorycacheTryGet()Method. The following is a modified version of the index method. The code is as follows:


        public IActionResult Index()
        {
            string key = "IDGKey";

            string obj;
            if (!cache.TryGetValue<string>(key, out obj))
            {
                obj = DateTime.Now.ToString();
                cache.Set<string>(key, obj);
            }

            ViewBag.Cache = obj;

            return View();
        }

There’s another one calledGetOrCreateMethod. It can be seen from the name. If you can’t get it, you will create one, as shown in the following code:


        public IActionResult Index()
        {
            cache.GetOrCreate<string>("IDGKey", cacheEntry =>
            {
                return DateTime.Now.ToString();
            });

            return View();
        }

By the way, except for the synchronous versionGetOrCreate, and an asynchronousGetOrCreateAsync

Cache expiration policy

You can specify an expiration policy for cached data, for example:Absolute expiration timeandSlide expiration timeThe former indicates the absolute survival time of the cached data, which will be removed as soon as the time arrives. The latter indicates that if the data is not accessed within the specified time interval, it will be removed. If you do not understand the mechanism, please refer to the expiration mechanism of session.

To set the expiration policy, you canMemoryCacheEntryOptionsClass, as shown in the following code:


        public IActionResult Index()
        {
            MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();

            cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);

            cacheExpirationOptions.Priority = CacheItemPriority.Normal;

            cache.Set<string>("IDGKey", DateTime.Now.ToString(), cacheExpirationOptions);

            return View();
        }

It’s worth noting that the abovePriorityWhen the memory of an application is insufficient, the priority of the low priority will be removed first. In addition to normal enumeration, there are other applications such as:Low, High, NeverRemove, exceptNeverRemoveThe others will be controlled by the recycling mechanism.

The new cache mechanism also provides a new way to solve this problemCallback functionInjection, which means that when the cache is removed due to expiration, the callback function you specified will be triggered automaticallyCallback functionDo some custom business logic in the cache, such as re injecting values into the cache, as shown in the following code:


        public IActionResult Index()
        {
            MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();

            cacheExpirationOptions.RegisterPostEvictionCallback((obj1, obj2, reason, obj3) =>
            {
                //callback

            }, this);

            cache.Set<string>("IDGKey", DateTime.Now.ToString(), cacheExpirationOptions);

            return View();
        }

You can even configure the dependency of two caches, for example, if one of themcache itemIf it is removed, you want the cache associated with it to be removed automatically. It seems that it is very nice and the space is limited. I will explain how to implement it in later articles. If you want to know, you can refer to Microsoft MSDN: https://docs.microsoft.com/en…

Translation link: https://www.infoworld.com/art…

More high quality dry goods: see my GitHub: csharptranslate