CORE API 限流,防止,链接数过多而崩溃。

今天有个项目,使用的是EF core API 跨域接口。但是遇到的问题就是发布到公司服务器后,外网访问率低的情况正常。访问过多,则会直接导致IIS应用程序池对应程序崩溃,停止运行。

1、程序限流

      1.1、NuGet下载引用 AspNetCoreRateLimit

      1.2、startup中添加配置

               

 1 #region IP限流配置
 2 
 3             // 存储IP计数器及配置规则
 4             services.AddMemoryCache();
 5             // 配置
 6             services.Configure<IpRateLimitOptions>(options =>
 7             {
 8                 //options.EnableEndpointRateLimiting = true; // true,意思是IP限制会应用于单个配置的Endpoint上,false,只能限制所有接口Endpoint只能为*
 9                 options.HttpStatusCode = 429; // 触发限制之后给客户端返回的HTTP状态码
10                 options.RealIpHeader = "X-Real-IP";
11                 options.ClientIdHeader = "X-ClientId";
12                 options.QuotaExceededResponse = new QuotaExceededResponse // 触发限制之后给客户端返回的数据
13                 {
14                     Content = "{{\"code\":-1,\"msg\":\"访问过于频繁,请稍后重试\"}}",
15                     ContentType = "application/json",
16                     StatusCode = 429
17                 };
18                 // 限制规则
19                 options.GeneralRules = new List<RateLimitRule>
20                 {
21                     new RateLimitRule
22                     {
23                         //Endpoint = "*:/signtoken",// 正则匹配规则,只针对签发token接口
24                         Endpoint = "*",
25                         Period = "1s",// 周期 s秒 m分钟 h时 d天
26                         Limit = 10,// 次数
27                     }
28                 };
29             });
30 
31             // 注入计数器和规则存储
32             services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
33             services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
34             // the clientId/clientIp resolvers use it.
35             services.AddHttpContextAccessor();
36             // 配置(计数器密钥生成器)
37             services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
38 
39             #endregion
ConfigureServices配置
1 // 启用限流,放在app.UseRouting();之前
2 app.UseIpRateLimiting();
Configure配置

 

 2、IIS配置

 

 

 

 

   

posted on 2020-11-19 16:50  木乃伊人  阅读(332)  评论(0编辑  收藏  举报

导航