/**
* 漏桶算法
*
* @author xubh
* @date 2019-04-10
* @mondify
* @copyright
*/
public class LeakyDemo {
private long timeStamp = System.currentTimeMillis();
/**
* 桶的容量
*/
private long capacity;
/**
* 水漏出的速度
*/
private long rate;
/**
* 當(dāng)前水量(當(dāng)前累積請求數(shù))
*/
private long water;
public boolean grant() {
long now = System.currentTimeMillis();
// 先執(zhí)行漏水邻寿,計算剩余水量
water = Math.max(0, water - (now - timeStamp) * rate);
timeStamp = now;
if ((water + 1) < capacity) {
// 嘗試加水,并且水還未滿
water += 1;
return true;
} else {
// 水滿蝎土,拒絕加水
return false;
}
}
}
/**
* 令牌桶算法
*
* @author xubh
* @date 2019-04-10
* @mondify
* @copyright
*/
public class TokenBucketDemo {
public long timeStamp = System.currentTimeMillis();
/**
* 桶的容量
*/
public long capacity;
/**
* 令牌放入速度
*/
public long rate;
/**
* 當(dāng)前令牌數(shù)量
*/
public long tokens;
public boolean grant() {
long now = System.currentTimeMillis();
// 先添加令牌
tokens = Math.min(capacity, tokens + (now - timeStamp) * rate);
timeStamp = now;
if (tokens < 1) {
// 若不到1個令牌,則拒絕
return false;
} else {
// 還有令牌,領(lǐng)取令牌
tokens -= 1;
return true;
}
}
}