需求描述
写一个1秒两个的限流工具类,2r/s
public class LimitHelper {
private int maxLimit;
private Semaphore semaphore;
private int timeoutSeconds;
public LimitHelper(int maxLimit, int timeoutSeconds) {
this.maxLimit = maxLimit;
semaphore = new Semaphore(maxLimit);
this.timeoutSeconds = timeoutSeconds;
this.autoRelease();
}
/**
* 每秒钟释放两个信号出来
*/
private void autoRelease() {
new Thread(() -> {
try {
while (true) {
TimeUnit.SECONDS.sleep(timeoutSeconds);
if (!semaphore.tryAcquire(1)) {
// 无信号了
semaphore.release(maxLimit);
}else {
// 池中有信号,并且消耗了一个,释放一个补偿
semaphore.release(1);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
public boolean acquire() {
try {
return semaphore.tryAcquire(1, timeoutSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
LimitHelper limitHelper = new LimitHelper(2, 1);
for (int i = 0; i < 5; i++) {
new Thread(() -> {
while (true) {
if (limitHelper.acquire()) {
System.out.println( System.currentTimeMillis() / 1000+ " " + Thread.currentThread().getName() + " 获取到令牌");
try {
// 业务处理
TimeUnit.MILLISECONDS.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} else {
System.out.println(System.currentTimeMillis() / 1000 + " "+Thread.currentThread().getName() + " 被限流了");
}
}
}).start();
}
}
}