• .Net Core使用AspNetCoreRateLimit实现限流


    1.添加Nuget程序包

     2.在start up中进行配置【有两种模式可选 存储在redis中会哦这内存中】

    // 需要从appsettings.json中加载配置
    
                services.AddOptions();
    
                // 存储IP计数器在内存中
    
                services.AddMemoryCache();
               //或者存储在redis中

      //services.AddDistributedRedisCache(options =>{

    //options.Configuration = "119.45.138.19:6379,password=123456,connectTimeout=5000,syncTimeout=10000";

                 //options.InstanceName = "WebRatelimit";
                 //});

    
                services.Configure<IpRateLimitOptions>(Configuration.GetSection("RateLimitingConfig"));
    
                services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
    
                services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
         
                 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
      
                 services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

    3.在appsetting.json中配置相关参数

      "RateLimitingConfig": {
        //false则全局将应用限制,并且仅应用具有作为端点的规则* 。 true则限制将应用于每个端点
        "EnableEndpointRateLimiting": true,
        //false则拒绝的API调用不会添加到调用次数计数器上  
        "StackBlockedRequests": false,
        //获取用户端的真实IP
        "RealIpHeader": "X-Real-IP",
        "ClientIdHeader": "X-ClientId",
        "HttpStatusCode": 200,
        "QuotaExceededResponse": {
          "Content": "{{\"code\":429,\"msg\":\"Visit too frequently, please try again later\",\"data\":null}}",
          "ContentType": "application/json",
          "StatusCode": 200
        },
       //ip白名单
        "IpWhitelist": [ "139.159.187.209" ],
        "EndpointWhitelist": [],
        "ClientWhitelist": [],
        "GeneralRules": [
          {
            "Endpoint": "*",
            "Period": "60s",
            "Limit": 0
          }
        ]
      }

    4.启用配置

    //位置放在控制器前面
    app.UseIpRateLimiting();
  • 相关阅读:
    204. Count Primes (Integer)
    203. Remove Linked List Elements (List)
    202. Happy Number (INT)
    201. Bitwise AND of Numbers Range (Bit)
    200. Number of Islands (Graph)
    199. Binary Tree Right Side View (Tree, Stack)
    198. House Robber(Array; DP)
    191. Number of 1 Bits (Int; Bit)
    190. Reverse Bits (Int; Bit)
    189. Rotate Array(Array)
  • 原文地址:https://www.cnblogs.com/wilsonNet/p/14803951.html
Copyright © 2020-2023  润新知