Skip to content

Instantly share code, notes, and snippets.

@lgolubyev
Created Jul 20, 2022
Embed
What would you like to do?
enum MyPolicyEnum
{
One,
Two,
Admin,
Default
}
PartitionedRateLimiter<string> limiter = PartitionedRateLimiter.Create<string, MyPolicyEnum>(resource =>
{
if (resource == "Policy1")
{
return RateLimitPartition.Create(MyPolicyEnum.One, key => new MyCustomLimiter());
}
else if (resource == "Policy2")
{
return RateLimitPartition.CreateConcurrencyLimiter(MyPolicyEnum.Two, key =>
new ConcurrencyLimiterOptions(permitLimit: 2, queueProcessingOrder: QueueProcessingOrder.OldestFirst, queueLimit: 2));
}
else if (resource == "Admin")
{
return RateLimitPartition.CreateNoLimiter(MyPolicyEnum.Admin);
}
else
{
return RateLimitPartition.CreateTokenBucketLimiter(MyPolicyEnum.Default, key =>
new TokenBucketRateLimiterOptions(tokenLimit: 5, queueProcessingOrder: QueueProcessingOrder.OldestFirst,
queueLimit: 1, replenishmentPeriod: TimeSpan.FromSeconds(5), tokensPerPeriod: 1, autoReplenishment: true));
}
});
RateLimitLease lease = limiter.Acquire(resourceID: "Policy1", permitCount: 1);
// ...
RateLimitLease lease = limiter.Acquire(resourceID: "Policy2", permitCount: 1);
// ...
RateLimitLease lease = limiter.Acquire(resourceID: "Admin", permitCount: 12345678);
// ...
RateLimitLease lease = limiter.Acquire(resourceID: "other value", permitCount: 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment