[英]How to set up a .NET 7 C# rate limiter per user if the user id is stored ONLY in the entity in the request body?
There is an API that accepts an entity with a previously unknown ID.有一个 API 接受一个以前未知 ID 的实体。 I need to configure the rate limiter so that entities with the same ID get into the queue.
我需要配置速率限制器,以便具有相同 ID 的实体进入队列。 I figured out how to create a window and a queue.
我想出了如何创建一个 window 和一个队列。 How to make a separate queue for each ID?
如何为每个 ID 创建一个单独的队列?
The entity is a JSON file.该实体是一个 JSON 文件。 The ID is inside the file.
ID 在文件中。
The following is written, but this forms one queue:下面写的,不过这个forms一个队列:
services.AddRateLimiter(options => options
.AddFixedWindowLimiter(policyName: "UserPolicy", options =>
{
options.PermitLimit = 1;
options.Window = TimeSpan.FromSeconds(10);
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 3;
}));
You can try using PartitionedRateLimiter
.您可以尝试使用
PartitionedRateLimiter
。 Something along these lines (not tested):这些方面的东西(未测试):
builder.Services.AddRateLimiter(options =>
{
options.AddPolicy("myRateLimiter1", context =>
{
var request = context.Request;
var partitionKey = "";
if (request.Method == HttpMethods.Post && request.ContentLength > 0)
{
request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
request.Body.Read(buffer, 0, buffer.Length);
//get body string here...
var requestContent = Encoding.UTF8.GetString(buffer);
// get partition key here... partitionKey = ...
request.Body.Position = 0; //rewinding the stream to 0
}
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: partitionKey,
factory: partition => new FixedWindowRateLimiterOptions
{
PermitLimit = 1,
Window = TimeSpan.FromSeconds(10),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 3
});
});
});
Though I would suggest to consider passing Id in some other way (headers) or resolve the limiter on the handler/BL level.尽管我建议考虑以其他方式(标头)传递 Id 或在处理程序/BL 级别解决限制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.