当前位置:网站首页>Webapi performance optimization

Webapi performance optimization

2022-06-25 10:05:00 @@Mr.Fu

One 、WebApi tuning

  • What is? WebApi tuning

    When the browser side requests WebApi It takes time for the server to read and write data , Shorten the time it takes , It's called WebApi tuning .

    Pictured :

 Insert picture description here

  • Purpose
    promote WebApi Performance of .

Two 、WebApi Application scenarios

  • scene

    Projects that are separated at the front and rear end .

3、 ... and 、WebApi Performance bottleneck positioning

  • Locate performance bottlenecks

    Please have a look at NetCore Performance troubleshooting article :https://blog.csdn.net/Fu_Shi_rong/article/details/123733415?spm=1001.2014.3001.5501

Four 、WebApi Performance optimization means 1 - Local cache

  • Single project

    Pictured :

 Insert picture description here

  • Realization

    • Design thinking

      When querying, first check whether there is data in the local cache , There's data coming back directly , Query the database when there is no data , Add the queried data to the local cache and return the data to the browser

    • Advantages and disadvantages

      • shortcoming

        Memory Is the cache in the server memory , If the concurrency is large and the query data is inconsistent , It will cause a very large memory , At the same time, it will cause GC Constantly reclaim this memory , because Memory Memory cannot be recycled due to static variables used internally ,GC Every time you recycle , It will consume once CPU resources , If GC The frequency of recycling is relatively high , That consumes CPU Resources will also grow , for example : current CPU The usage rate of is 100%,GC consumed 70%CPU resources , Then our throughput is only 30%, The performance of processing requests is greatly reduced .

        • Solution
          1. Use time for space to solve , Set the cache time .
          2. Set cache size
          3. Set the size of a single cache , And set the automatic expiration time
      • advantage

        Data reading and writing speed and time are reduced , Improved performance .

  • Implementation steps

    • Install cache Nuget package

      Microsoft.Extensions.Caching.Memory  
      
    • Startup register

      ConfigureServices Method 
      Service.AddMemoryCache(options=>{
         options.SizeLimit = 1024*1024*100; // Set cache size 
      });
      
    • Inject in the scene of use

       Inject... Into the construction method 
      
      private readonly IMemoryCache memoryCache;
      
       Constructors   (IMemoryCache _memoryCache)
      {
        
       memoryCache =_memoryCache;
      }
      // Test object  
       Person per = new Person();
      // Query cache method  
      //memoryCache.Get<Person>(key); 
      // To prevent multithreading concurrency 
      bool flag = memoryCache.TryGetValue< Cache object >(key,out per);
      //true: There's data   false: No data 
      // Limit cache size 
      var  cacheEntryOptions = new MemoryCacheEntryOptions().
      // Set the size of a single cache 
      SetSize(1024).
      // Set expiration time    Automatic failure 
      SetSlidingExpiration(TimeSpan.FromSeconds(3));
      // Add cache 
      memoryCache.Set<Person>(key,value,cacheEntryOptions);
      
  • Solving the first request takes time

    When the project starts , Add data from the database to the cache

    • Code implementation

      // Class inheritance  IHostService  
      // And in Startup Class registration 
      

5、 ... and 、WebApi Performance optimization means 2 - Distributed cache

  • programme
    • Please read this article .https://blog.csdn.net/Fu_Shi_rong/article/details/123930343?spm=1001.2014.3001.5501

6、 ... and 、WebApi Performance optimization means 3 -Http cache ( Response cache )

  • programme

    • Negotiate the cache

      • install Nuget package

        Marvin.Cache.Headers
        
      • stay Startup Class only register

        ConfigureServices Method registration 
        Service.AddHttpCacheHeaders((options)=>{options.MaxAge = ....;// Set expiration time    Default 60s
                                                options.CacheLocation = ....;//public   Public   private   Private can only be used by the current client 
                                                options.NoStore= ...;//   Set response header information     No local cache 
                                                options.NoTransform= ....;// Set the request header information  
                                                },
                                    (options1)=>{}); 
        Configure Method to start and store verification information 
        app.UseHttpCacheHeaders();
        
      • Add code to the controller method

        HttpContext.Response.Headers.Add("cache-control","max-age=60,public"); // Whether to enable buffered data storage    Set cache time  
        HttpContext.Response.Headers.Add("etag",Value);// check 
        HttpContext.Response.Headers.Add("last-modified","Mon,24 Dec 2022 09:49:49 GMT");
        
      • principle

        When the client first requests the server , After the server responds , The server will write two parameters to the response header 【1、 Whether to enable cache storage data 2、 check 】 And store it to the client , The client will store the data in the cache warehouse ; When the client requests the server for the second time , Will etag Send it to the server for verification , If two etag They are equal. , The server will return to the client 304, The client will get data from the cache Repository .

      • scene

        Immutable data use .

      • defects

        It will waste a lot of client and server interaction .

  • Mandatory cache [ Not commonly used ]

    • step

      • install Nuget package

        Marvin.Cache.Headers
        
      • stay Startup class ConfigureServices Method registration

        ConfigureServices Method registration 
        Service.AddHttpCacheHeaders((options)=>{
          options.MustRevalidate = true;  // In a global way    Not recommended 
        }); 
        Configure Method to start and store verification information 
        app.UseHttpCacheHeaders();
        
      • Add code to the controller method

        HttpContext.Response.Headers.Add("cache-control","max-age=60,public,must-revalidate");
        
      • Use... For a controller

        // Add a property to the controller method 
        [HttpCacheExpiration(CacheLocation = CacheLocation.Public,MaxAge=60)]   Set up NoStore = true   Don't walk the cache 
        [HttpCacheValidation(MustRevalidate = true)]
        
    • scene

      1. Dictionary data
      2. Static resources Pictures, etc
      3. js or css file ​

7、 ... and 、WebApi Performance optimization means 4 - data compression ( Respond to )

  • step

    • stay Startup class ConfigureServices Method registration

      // Response data compression 
      services.AddResponseCompression();
      
    • stay Startup class Configure Method

      // It must be written at the beginning of the middleware 
      app.UseResponseCompression();
      
  • The purpose of data compression

    When data is transmitted , Reduce transmission bandwidth , Lifting performance .

  • scene

    Data compression can be used whenever data transmission is involved .

原网站

版权声明
本文为[@@Mr.Fu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250915501320.html