简单的限流 java实现 RateLimiter
2018-11-16 本文已影响0人
乘以零
1. 基于QPS的限流 即单位时间的请求数不能超过一个阈值
package com.multiplyzero.mz.core.rpc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* QpsRateLimiter
*
* @author xy.z@qq.com
*
* @since 2018年11月16日 上午10:09:12
*/
public class QpsRateLimiter {
private long lastTime;
private long interval;
private AtomicInteger remaind;
private int rate;
public QpsRateLimiter(int rate, long interval, TimeUnit unit) {
this.rate = rate;
this.interval = unit.toMillis(interval);
this.lastTime = System.currentTimeMillis();
this.remaind = new AtomicInteger(rate);
}
public boolean allowable() {
long now = System.currentTimeMillis();
if (now > lastTime + interval) {
remaind.set(rate);
lastTime = now;
}
int value = remaind.get();
boolean flag = false;
while (value > 0 && !flag) {
flag = remaind.compareAndSet(value, value - 1);
value = remaind.get();
}
return flag;
}
}
2.基于并发访问的限流 即并发数不能超过阈值 这个记得在finally中要release资源
package com.multiplyzero.mz.core.rpc;
import java.util.concurrent.Semaphore;
/**
*
* ExecuteRateLimiter
*
* @author xy.z@qq.com
*
* @since 2018年11月16日 上午10:11:23
*/
public class ExecuteRateLimiter {
private Semaphore rate;
public ExecuteRateLimiter(int rate) {
this.rate = new Semaphore(rate);
}
public boolean allowable() {
boolean allowable = rate.tryAcquire(1);
return allowable;
}
public void release() {
rate.release(1);
}
}