1024programmer Asp.Net .net Review the past and learn the new [14]: Asp.Net Core WebAPI cache

.net Review the past and learn the new [14]: Asp.Net Core WebAPI cache

.net Review the past and learn the new [14]: Asp.Net Core WebAPI cache

1. Cache

Caching refers to the act of storing data in an intermediary tier that makes subsequent data retrieval faster. Conceptually, caching is a performance optimization strategy and design consideration. Caching can significantly improve application performance by improving the readiness of data that changes infrequently (or is expensive to retrieve).

二、RFC9111

In the latest cache control specification document RFC9111, the specifications for browser cache and server cache control are described in detail, including the most important response message header Cache-Control.

The setting of this header will affect our cache, both on the browser side and on the server side.

RFC911: https://www.rfc-editor.org/rfc/rfc9111#name-cache-control

image

3. Web-side cache

In Cache-Control, if you set max-age=10, it means telling the browser to cache for 10s. Why does the browser recognize this? The front and back ends we mentioned above must be implemented according to the RFC standard specification, which is a unified socket for the hardware, otherwise the other generated ones will not be used.

Then in Asp.net Core, you only need to add ResponseCacheAttribute to the interface and set the max-age time.

First build an Asp.Net Core WebAPI project and write a Get interface for obtaining students.

image

namespace WebAPI_Cache.Controllers
 {
     [ApiController]
     [Route("[controller]")]
     public class CacheController : ControllerBase
     {

         publicCacheController()
         {

         }

         [HttpGet]
         public ActionResult GetStudent()
         {

             return newStudent()
             {
                 Id = 1,
                 Name = "Test",
                 Age = Random.Shared.Next(0, 100),
             };
         }
     }
 }
 
namespace WebAPI_Cache.Model
 {
     public class Student
     {
         public int Id { get; set; }
         public string? Name { get; set; }
         public int Age { get; set; }
     }
 }
 

In the interface, I return a random number between 1 and 100 for the age of Student. Start the project test, and the age returned by two calls in a short period of time are different

First age:

image

Second age:

image

When I add [ResponseCache(Duration = 10)] to the interface method, and the information returned by calling the interface again shows that there is already cache-control: public,max-age= 10 Header.

image

And among my requests within 10 seconds, only the first request was made to the server, and the others were fetched from the cache. Check the edge browser network access as follows:

image

Four. Server Cache

Web page caching is placed on the browser side, which is useful for single requests, but what if there are multiple different front-end requests. At this time we can place the cache in the back-end service and configure the response caching middleware in ASP.NET Core.

In Program.cs, add the response caching middleware service AddResponseCaching to the service collection and configure the application. If CORS middleware is used, UseCors must be called before UseResponseCaching.

If the header contains Authorization and Set-Cookie headers, it will not be cached, because the cache of these user information will cause data confusion.

image

Then add the ResponseCache attribute to the interface we need the server to cache. Just like setting the browser cache, there are other parameters that can be set. We tested through two processes, one using the browser swagger and the other using postman. We can see that the age of both requests is equal to 18. So it can be determined that there is indeed a cache on the server side.

image

But when testing with postman, remember to check off Send no-cache header in settings. If you don’t remove it, Cache-Control will be included in the request header when sending. :no-cache, so that even if the server has a cache, it will notUse caching.

image

For the browser, it is equivalent to disabling the cache. If the cache is disabled, the request header sent will also carry Cache-Control:no-cache, and the server will not see no-cache. The cache will be used again to respond.

This agreement is the specification of RFC9111, so this backend caching strategy is relatively useless. If the user disables caching, it will be useless, so we can also use memory caching.

5. Memory cache

The memory cache is based on IMemoryCache. IMemoryCache represents a cache stored in the web server’s memory.

  • First Nuget installation package
Install-Package Microsoft.Extensions.Caching.Memory
 
  • Add dependencies in Program.cs
builder.Services.AddMemoryCache();
 
  • Cache data
    I add a Post method to simulate id query Student

image

In this way, I cache the data in the memory. I can set the absolute expiration time of the cache or set the sliding expiration. We will see the use of the expiration strategy later.

Six, cache breakdown

Cache breakdown refers to when a hotspot key expires at a certain point in time, and there are a large number of concurrent requests for this key at this point in time, or non-existent data is queried, which is not in the cache, resulting in a large number of The requests hit the database causing database pressure.

We can see from the writing method in the memory cache above that if the query cache is equal to null, the data will be queried again (I am just simulating here, and there is no actual database query). If such a violent request There will be problems with attacking.

For this problem we can use the ImemoryCache‘s GetOrCreate method, of course it also has an asynchronous method. Pass the cached key and func delegate method return value through this method to query and cache. If the returned null is not queried, it will also be stored in the cache to prevent malicious queries for non-existent data.

 [HttpPost]
         public ActionResult GetStudent2(int id)
         {
             //Query and create cache
             var student = _memoryCache.GetOrCreate("student_" + id, t =>
             {
                 t.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(20);
                 //Simulate that only id=1 has data
                 if (id == 1)
                 {
                     return newStudent()
                     {
                         Id = 1,
                         Name = "Test",
                         Age = Random.Shared.Next(0, 100),
                     };
                 }
                 else
                 {
                     //Others return empty, but empty values ​​will also be cached. For example, queries id=2, id=3 will be cached.
                     return null;
                 }

             });
             if (student == null)
             {
                 return NotFound("Not found");
             }
             else
             {
                 return student;
             }
         }
 

Seven. Cache Avalanche

Cache avalanche refers to the expiration time of a large amount of data in the cache, causing all requests to query the database, and the amount of query data is huge, causing excessive pressure on the database and even downtime.

For avalanche situations, our caching strategy is mainly to set the expiration time. For some unimportant sites, such as news websites, we will set the absolute expiration time AbsoluteExpiration to be longer.

For those who need a certain degree of flexibility and can invalidate data when requests are infrequent, we can use sliding expiration time, that is, if requests are frequent, the sliding expiration time will be set.

Of course, in order to prevent the sliding time from ever expiring, you can also use a mixture of the two methods. In the above example, we set the absolute expiration time to 20 seconds, and we set the sliding expiration to 5 seconds. If there is continuous access within 5 seconds, it will continue until the absolute expiration of 20 seconds.

Then if no one accesses it, it will expire after 5 seconds, so that the latest data can be queried in time next time the data is accessed.

image

Eight, distributed cache

The above caching solution is enough to deal with some small and simple business systems, but if you are deploying a distributed service, then the data accessed by the memory cache is the cache of a single server.

You may need requests from multiple servers to be consistent, to remain valid after server restarts and application deployments, to not use local memory, etc.

At this time we can use third-party caches, such as memecache, Redis, etc. Asp.Net Core uses the IDistributedCache interface to interact with the cache.

  • NuGet installation package
Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
 
  • Register IDistributedCache implementation in Program.cs
    image

Configuration: Configuration for the connection.
InstanceName: is the storage key prefix.

Write the test method GetStuden3

image

IDistributedCache accepts string keys and adds or retrieves cache items in the form of byte[] arrays, so the data is accessed in the form of byte[], but it has been extended with a string type method for use. I use strings here. operate.

The above are the important points and basic usage methods about using cache in ASP.NET Core. For detailed parameters and documents, please refer to the official document: Overview of Caching in ASP.NET Core

Author: Sun Quan

Source: https://www.cnblogs.com/SunSpring/p/17848185.html

If you like the article, please click to recommend it. Your encouragement is very useful to me!

The copyright of this article belongs to the author. Reprinting must provide a link to the original text in an obvious position on the article page.

ul>

Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
 
  • Register IDistributedCache implementation in Program.cs
    image

Configuration: Configuration for the connection.
InstanceName: is the storage key prefix.

Write the test method GetStuden3

image

IDistributedCache accepts string keys and adds or retrieves cache items in the form of byte[] arrays, so the data is accessed in the form of byte[], but it has been extended with a string type method for use. I use strings here. operate.

The above are the important points and basic usage methods about using cache in ASP.NET Core. For detailed parameters and documents, please refer to the official document: Overview of Caching in ASP.NET Core

Author: Sun Quan

Source: https://www.cnblogs.com/SunSpring/p/17848185.html

If you like the article, please click to recommend it. Your encouragement is very useful to me!

The copyright of this article belongs to the author. Reprinting must provide a link to the original text in an obvious position on the article page.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/net-review-the-past-and-learn-the-new-14-asp-net-core-webapi-cache/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索