当前位置: 首页 > 滚动 > >正文

【故障补牢】贪吃的 Bing 爬虫,限量供应的应对措施 环球滚动

来源:博客园    时间:2023-05-09 09:24:37


(资料图片)

相对于【故障公告】,【故障补牢】分享的是园子在发生故障后采取的亡羊补牢措施。

在上次被微软 Bing 爬宕机后(详见 【故障公告】被放出的 Bing 爬虫,又被爬宕机的园子),我们采取了2个应对措施,然后解除了对 Bing 爬虫的屏蔽。

措施1:限流——采用滑动窗口进行限流

我们之前采用的限流措施没有采用滑动窗口,只能防君子不能防小人,比如限制同一个IP一天只能请求2万次,但如果遇到大胃口的爬虫,1秒请求2万次,虽然没有超过限制,但服务器已趴下。

我们通过 ASP.NET Core 内置的 rate limiting middleware 进行滑动窗口限流,参考博文 ASP.NET Core rate limiting middleware in .NET 7

services.AddRateLimiter(    _ =>    {        _.GlobalLimiter = PartitionedRateLimiter.CreateChained(            PartitionedRateLimiter.Create(                _ => RateLimitPartition.GetSlidingWindowLimiter(                    "total",                    _ => new SlidingWindowRateLimiterOptions()                    {                        AutoReplenishment = true,                        PermitLimit = limitOptions.TotalPermitLimit,                        QueueLimit = 0,                        Window = TimeSpan.FromSeconds(limitOptions.WindowSize),                        SegmentsPerWindow = limitOptions.WindowSize,                        QueueProcessingOrder = QueueProcessingOrder.OldestFirst                    })),            PartitionedRateLimiter.Create(                context => RateLimitPartition.GetFixedWindowLimiter(                    partitionKey: context.GetUserIp() ?? "unspecified",                    factory: _ => new FixedWindowRateLimiterOptions                    {                        AutoReplenishment = true,                        PermitLimit = limitOptions.PermitLimit,                        QueueLimit = limitOptions.QueueLimit,                        Window = TimeSpan.FromSeconds(limitOptions.WindowSize),                        QueueProcessingOrder = QueueProcessingOrder.OldestFirst                    })));        _.OnRejected = (context, _) =>        {            context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;            return default;        };    });

措施2:隔离——专用 pod 限制计算资源、专用负载均衡限制带宽

借助 k8s 的资源隔离能力,部署专用的 pod 给 Bing 爬虫使用,最多把 pod 爬挂,不会造成服务器宕机,对其他应用 pod 毫无影响。

部署专门的负载均衡给 Bing 爬虫通行,这样可以避免因爬虫抢占带宽而造成其他正常请求无法正常响应,而且可以通过限制带宽控制爬虫的并发请求量以及带宽成本。

X 关闭

推荐内容

最近更新

Copyright ©  2015-2022 南方洁具网  版权所有    
备案号:粤ICP备18023326号-21     
 联系邮箱:855 729 8@qq.com