• .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();
  • 相关阅读:
    杭电1466------简单的dp
    hdu2037-----------贪心, 活动安排问题
    两个钟表问题。
    杭电HDU1042(有点坑的高精度)
    hd1496---->这道题是水水的数论吗?
    LightOJ::1077 -----奇妙的最大公约数
    并查集练兵场
    欧拉函数
    位运算---水题
    矩阵快速幂
  • 原文地址:https://www.cnblogs.com/zhangdongwei/p/14803951.html
Copyright © 2020-2023  润新知