漏桶算法(限流)

桶有进有出,用户请求即为进,服务消费即为出,桶本身有个最大容量,当超过这个最大容量会进行熔断。

算法代码如下:

double rate; // leak rate in calls/s
double burst; // bucket size in calls
long refreshTime; // time for last water refresh
double water; // water count at refreshTime
refreshWater() {
long now = getTimeOfDay();
//水随着时间流逝,不断流走,最多就流干到0.
water = max(0, water- (now - refreshTime)*rate);
refreshTime = now;
}
bool permissionGranted() {
refreshWater();
if (water < burst) { // 水桶还没满,继续加1
water ++;
return true;
} else {
return false;
}
}

其中rate为单位时间内服务消费的个数
rate = (处理请求个数)/花费的时间 (毫秒)

参考链接:https://blog.csdn.net/tianyaleixiaowu/article/details/74942405

你可能感兴趣的:(漏桶算法(限流))