zoukankan      html  css  js  c++  java
  • .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();
  • 相关阅读:
    [题解]luogu_P4198_楼房重建(线段树logn合并
    [题解]luogu_P3084(单调队列dp
    [题解]luogu_P3084(差分约束/梦想spfa
    [题解/模板]POJ_1201(差分约束
    [题解]luogu_P5059(矩乘
    [题解]luogu_P5004跳房子2(矩乘递推
    CF1042A Benches(二分答案)
    8.24考试总结
    NOIP2017题目
    「LG3045」「USACO12FEB」牛券Cow Coupons
  • 原文地址:https://www.cnblogs.com/zhangdongwei/p/14803951.html
Copyright © 2011-2022 走看看