ASP.NET Core MVC cache from entry to proficiency

With the development of technology, ASP.NET Core MVC has also been launched for a long time. After continuous version update iterations, it has become more and more perfect. This series of articles mainly explains the related content involved in the process of ASP.NET Core MVC development B/S system. It is suitable for beginners, school graduates, or other personnel who want to engage in ASP.NET Core MVC system development.

After the explanations of the previous articles, I have a preliminary understanding of ASP.NET Core MVC project creation, startup and operation, and naming conventions, creating controllers, views, models, receiving parameters, passing data ViewData, ViewBag, routing, page layout, wwwroot and client libraries, Razor syntax, EnityFrameworkCore and databases, HttpContext, Request, Response, Session, serialization, file upload, automatic mapping, Html auxiliary tags, model validation, authentication, authorization basics, entry to Identity, logs Management, Filter (filter) and other content, continue to explain caching and other related content in ASP.NET Core MVC today, for learning and sharing only .

Advantages of caching

In the application, using the cache has the following advantages:

  1. Improve application access speed
  2. For data that is not easily changed

cache classification

According to the scope of application and storage method of the cache, it can be divided into the following categories:

  1. Memory cache: This method is to cache the content in the web server, which is mainly applicable to single-server programs, and the data in the cache will also be lost after the server is restarted.
  2. Cache server: For a distributed web system, the way of caching and in-memory will cause inconsistency in the cache content in each web server. Generally, there will be an independent cache server, such as Redis, SQL Server, etc. to store the cache. The content in the cache server will not change with the restart of the web server.
  3. Client: Caching on the client is generally implemented through Header, or through localStorage, Cookie, etc. ( Not to be explained yet )

memory cache

In-Memory cache, which caches data in the memory of the web server, is suitable for programs deployed on a single server. In the ASP.NET Core MVC program, the steps to use the memory cache are as follows

1. Add cache service

In the Program.cs startup program, add the non-distributed memory cache service as follows:

//内存缓存
builder.Services.AddMemoryCache();

2. Inject the cache interface

In the memory cache controller that needs to be used, add the memory cache interface IMemoryCache injection, as follows:

private readonly ILogger<HomeController> _logger;

private readonly IMemoryCache _memoryCache;//内存缓存接口

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

3. Get/set cache

Where caching is used, getting and setting the cache looks like this:

public IActionResult Index()
{

    if(!_memoryCache.TryGetValue("citys",out List<City> cityList))
    {
        cityList = GetCitys();
        var memoryCacheEntryOptions = new MemoryCacheEntryOptions();
        memoryCacheEntryOptions.SetAbsoluteExpiration(TimeSpan.FromSeconds(10));
        memoryCacheEntryOptions.RegisterPostEvictionCallback((object key, object value, EvictionReason reason, object state) =>
        {
            //在被清除缓存时,重新回调,重新填充
            _logger.LogInformation("缓存被清除了.");
        }, this);
        _memoryCache.Set("citys", cityList, memoryCacheEntryOptions);
    }
    ViewBag.Citys = cityList;
    return View();
}

4. Parameter description

MemoryCacheEntryOptions in the example is mainly used to set the memory cache parameters, mainly the following parameters can be set:

  1. AbsoluteExpiration sets the absolute expiration time
  2. SlidingExpiration sliding expiration time
  3. PostEvictionCallbacks callback function when the cache is cleared

distributed cache

A distributed cache is a cache shared by multiple application servers, usually maintained as an external service to the application servers that access it. Distributed caching can improve the performance and scalability of ASP.NET Core apps, especially when the app is hosted by a cloud service or server farm.

Distributed caching has several advantages over other caching schemes that store cached data on a single application server. Advantages of Distributed Cache

  1. No Sticky Session required
  2. Scalable and applicable to the deployment of multiple web servers.
  3. Independent storage, the restart of the web server will not affect the cache
  4. better performance

1. Distributed cache prerequisites

Add a package reference for the distributed cache provider used:

  • For the Redis distributed cache, Microsoft.Extensions.Caching.StackExchangeRedis.
  • For SQL Server, see Microsoft.Extensions.Caching.SqlServer.
  • For NCache distributed caching, NCache.Microsoft.Extensions.Caching.OpenSource.

This example mainly introduces Redis distributed cache.

2. Environment construction

To use Redis for caching, you first need to build a Redis environment. For the Redis environment, please refer to the previous article:

  • Redis installation and startup: https://www.cnblogs.com/hsiang/p/14224484.html
  • Redis basic commands: https://www.cnblogs.com/hsiang/p/14269906.html
  • Redis configuration file: https://www.cnblogs.com/hsiang/p/14287098.html
  • Redis transaction: https://www.cnblogs.com/hsiang/p/14311126.html

3. Install dependent packages

Redis distributed cache, you need to install the third-party dependency package Microsoft.Extensions.Caching.StackExchangeRedis, as follows:

4. Add distributed cache service

Add the StackExchangeRedisCache service, and configure the Redis connection information and InstanceName instance name through Configruation. As follows:

//分布式缓存
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "192.168.1.6:6379";
    options.InstanceName = "redis";
});

5. Inject the distributed cache interface

In the Controller, inject the distributed cache interface IDistributedCache, as shown below:

private readonly IDistributedCache _distributedCache;

public HomeController(ILogger<HomeController> logger ,IDistributedCache distributedCache)
{
    _logger = logger;
    _distributedCache = distributedCache;
}

6. Get/set cache

Where caches are used, GetString and SetString caches look like this:

public IActionResult Index()
{
    var cityList = new List<City>();
    var obj = _distributedCache.GetString("citys");
    if (string.IsNullOrEmpty(obj))
    {
        cityList = GetCitys();
        DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
        options.SetAbsoluteExpiration(TimeSpan.FromSeconds(60));
        obj = JsonConvert.SerializeObject(cityList);
        _distributedCache.SetString("citys", obj,options);
    }
    cityList = JsonConvert.DeserializeObject<List<City>>(obj);
    ViewBag.Citys = cityList;
    return View();
}

7. Run the tests

Run the program and open Home/Index by default in the browser. The city list information is obtained from the database for the first time, and it will be obtained from the cache when it is obtained again. As follows:

 Check on the Redis server, you can find:

1. The Key stored in the cache server is prefixed with the configured InstanceName.

2. Although the code is stored through SetString, because the stored JSON serialized object, Redis automatically recognizes the object type as hash.

3. The stored Chinese is transcoded in the cache server.

reference article

Official document: https://learn.microsoft.com/zh-cn/aspnet/core/performance/caching/overview?view=aspnetcore-6.0

The above is the whole content of ASP.NET Core MVC cache from entry to mastery.

Guess you like

Origin blog.csdn.net/fengershishe/article/details/131349956