ibatis里面流控的实现

ibatis里面的流控实现是通过Throttle这个类来实现,既信号量,实例化时指定最大的访问量,每次请求时从这里获取一个信号量,如果已经达到阈值将阻塞或者抛出异常,以免大量的请求导致服务当机,每次请求时申请一个,请求结束返回,既信号量的实现,代码如下



申请资源
public void increment() {
synchronized (LOCK) {
long totalWaitTime = 0;
while (count >= limit) {
if (maxWait > 0) {
long waitTime = System.currentTimeMillis();
try {
LOCK.wait(maxWait - totalWaitTime);
} catch (InterruptedException e) {
//ignore
}
totalWaitTime += System.currentTimeMillis() - waitTime;
if (totalWaitTime > maxWait) {
throw new RuntimeException("Throttle waited too long (" + totalWaitTime + " milliseconds) for lock.");
}
} else {
try {
LOCK.wait();
} catch (InterruptedException e) {
//ignore
}
}
}
count++;
}
}

释放资源
/**
* Remove a reference
*/
public void decrement() {
synchronized (LOCK) {
count--;
LOCK.notify();
}
}

客户端调用方式

/**
* Pop an object from the pool
* @return - the Object
*/
public Object pop() {
throttle.increment();
return pool.remove(0);
}

/**
* Push an object onto the pool
* @param o - the object to put into the pool
*/
public void push(Object o) {
if (o != null && o.getClass() == type) {
pool.add(o);
throttle.decrement();
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值