if (this.limitSize <= 0)
this.limitSize = 100;
if (this.maxTPS <= 0)
this.maxTPS = 1;
limitedQueue = new LimitedQueue<object>(limitSize);
cancelToken = new CancellationTokenSource();
task = Task.Factory.StartNew(new Action(TokenProcess), cancelToken.Token);
}
private void TokenProcess()
{
int sleep = 1000 / maxTPS;
if (sleep == 0)
sleep = 1;
DateTime start = DateTime.Now;
while (cancelToken.Token.IsCancellationRequested == false)
{
try
{
if (limitedQueue.Count > 0)
{
lock (lckObj)
{
if (limitedQueue.Count > 0)
limitedQueue.Dequeue();
}
}
}
catch
{
}
finally
{
if (DateTime.Now - start < TimeSpan.FromMilliseconds(sleep))
{
int newSleep = sleep - (int)(DateTime.Now - start).TotalMilliseconds;
if (newSleep > 1)
Thread.Sleep(newSleep - 1); //做一下时间上的补偿
}
start = DateTime.Now;
}
}
}
public void Dispose()
{
cancelToken.Cancel();
}
public bool Request()
{
if (limitedQueue.Count >= limitSize)
return false;
lock (lckObj)
{
if (limitedQueue.Count >= limitSize)
return false;
return limitedQueue.Enqueue(new object());
}
}
}
调用方法:
var service = LimitingFactory.Build(LimitingType.LeakageBucket, 500, 200);
while (true)
{
var result = service.Request();
//如果返回true,说明可以进行业务处理,否则需要继续等待
if (result)
{
//业务处理......
}
else
Thread.Sleep(1);
}
两类限流算法虽然非常相似,但是还是有些区别的,供大家参考!
漏桶算法能够强行限制数据的传输速率。在某些情况下,漏桶算法不能够有效地使用网络资源。因为漏桶的漏出速率是固定的。
令牌桶算法能够在限制数据的平均传输速率的同时还允许某种程度的突发传输.