c# .net
c# .net Leaky Bucket
kimbs0301
2024. 7. 20. 17:06
클라이언트 요청 제한 Leaky Bucket
public class LeakyBucket
{
private readonly int Capacity;
private int Used;
private readonly long LeakInterval;
private long LastLeakTime;
public LeakyBucket(int maxRequestPerSecond)
{
Capacity = maxRequestPerSecond;
Used = 0;
LeakInterval = (1000 / maxRequestPerSecond) * TimeSpan.TicksPerMillisecond;
LastLeakTime = DateTime.UtcNow.Ticks;
}
public bool Allow()
{
// Leak
long now = DateTime.UtcNow.Ticks;
if (now > LastLeakTime)
{
long leaks = (now - LastLeakTime) / LeakInterval;
if (leaks > 0L)
{
if (Used <= leaks)
Used = 0;
else
Used -= (int) leaks;
LastLeakTime = now;
}
}
if (++Used >= Capacity)
return false;
return true;
}
}