• .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();
  • 相关阅读:
    js压缩上传图片
    理解clientWidth,offsetWidth,clientLeft,offsetLeft,clientX,offsetX,pageX,screenX
    图片转换成base64预览
    用mint ui去实现滚动选择日期并可以关闭拾取器
    CSS制作波浪线
    vue实现星级评价效果
    Intellij IDEA 安装lombok及使用详解
    Linux常用命令
    SpringBoot集成MyBatisPlus
    SpringBoot集成MyBatisPlus
  • 原文地址:https://www.cnblogs.com/zhangdongwei/p/14803951.html
Copyright © 2020-2023  润新知