【问题标题】:How to create a Semaphoreslim instance on application startup and use the same instance across all the requests?如何在应用程序启动时创建 Semaphoreslim 实例并在所有请求中使用相同的实例?
【发布时间】:2020-08-07 17:46:46
【问题描述】:

我有一个场景,我必须将并行 3rd 方 API 调用的数量一次限制为 200 个。为此,我使用了 SemaphoreSlim 并将可以执行代码块的线程数限制为 200。

这适用于单个用户/请求。但是如果同时有多个请求呢?

SemaphoreSlim 等待和释放之间的代码块是否在任何时间点/任何时候都只允许 200 个线程?请求数还是允许每个请求 200 个线程?

如果是通过请求,那么如何在应用程序启动时创建 SemaphoreSlim 实例,以便我可以对所有请求使用相同的实例?

【问题讨论】:

  • 听起来这行不通,应该首先在 Web 服务器上。听起来应该将其卸载到某种形式的外部服务

标签: c# .net .net-core parallel-processing asp.net-web-api2


【解决方案1】:

如果您想限制您的请求。 Asp.net 核心有一个速率限制实现,可以在 IP 级别或资源级别进行。这将取决于您要如何配置它。这将防止对您的 Web 应用程序/api 资源的恶意攻击

基本上你需要安装这个包

dotnet add package AspNetCoreRateLimit

你可以在 ConfigureServices 上做

services.RegisterLimitAndThrottlingMvcConfiguration();

这是扩展方法的实现

private static IServiceCollection RegisterLimitAndThrottlingMvcConfiguration(this IServiceCollection container,
            ServiceLifetime lifeTime = ServiceLifetime.Scoped)
        {
            //rate limiting
            //to store the counters and rules in memory
            container.AddMemoryCache();

            //configuring the options
            container.Configure<IpRateLimitOptions>(options =>
            {
                options.GeneralRules = new List<RateLimitRule>
                {
                    //any resource limit 1000 request every 5 min
                    new RateLimitRule
                    {
                        Endpoint = "*",
                        Limit = 1000,
                        Period = "5m"
                    },
                    //200 request every 10 seconds
                    new RateLimitRule()
                    {
                        Endpoint = "*",
                        Limit = 200,
                        Period = "10s"
                    }
                };
            });

            container.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
            container.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

            return container;
        }

并在Configure方法上设置中间件

//for limiting(header -> X-Rate-Limit- Limit, X-Rate-Limit-Remaining, X-Rate-Limit-Reset
app.UseIpRateLimiting();

为了限制你可以在这个链接limiting找到一篇好文章

【讨论】:

  • 感谢您的详细解释。
【解决方案2】:

我不认为创建全局信号量并以这种方式干扰 ASP.NET 管理线程池的方式会很好。

快速搜索后,我发现了这个关于如何限制并发连接的页面,但我不熟悉它,所以这只是一个猜测: https://www.oreilly.com/library/view/mastering-aspnet-core/9781787283688/f460937d-fa5e-439b-afa8-d0a417abc1ea.xhtml

在 Program.cs 中是单行添加:

【讨论】:

  • 神奇的问题是:当达到 200 标记时会发生什么?如果有人尝试连接到该服务,他们会收到错误吗?大概。我认为这不是 OP 想要的。
  • 我猜服务器会向客户端返回 503 状态码,因为 http 想要保持连接 util 将在服务器端有空闲线程
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2010-09-19
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多