/**
* 漏桶算法
*
* @author xubh
* @date 2019-04-10
* @mondify
* @copyright
*/
public class LeakyDemo {
private long timeStamp = System.currentTimeMillis();
/**
* 桶的容量
*/
private long capacity;
/**
* 水漏出的速度
*/
private long rate;
/**
* 当前水量(当前累积请求数)
*/
private long water;
public boolean grant() {
long now = System.currentTimeMillis();
// 先执行漏水,计算剩余水量
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;
/**
* 当前令牌数量
*/
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 {
// 还有令牌,领取令牌
tokens -= 1;
return true;
}
}
}