You've already forked FrameTour-BE
bug修复
This commit is contained in:
@ -0,0 +1,32 @@
|
||||
package com.ycwl.basic.ratelimiter;
|
||||
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class FixedRateLimiter {
|
||||
private final Semaphore semaphore = new Semaphore(1);
|
||||
private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
|
||||
|
||||
public FixedRateLimiter(int rate, TimeUnit timeUnit) {
|
||||
// 启动一个线程每0.5秒释放一个许可
|
||||
scheduler.scheduleAtFixedRate(() -> {
|
||||
synchronized (semaphore) {
|
||||
if (semaphore.availablePermits() < 1) {
|
||||
semaphore.release(1);
|
||||
}
|
||||
}
|
||||
}, rate, rate, timeUnit);
|
||||
}
|
||||
|
||||
public void acquire() throws InterruptedException {
|
||||
synchronized (semaphore) {
|
||||
semaphore.acquire();
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
}
|
||||
}
|
@ -12,14 +12,15 @@ public class SlidingWindowRateLimiter {
|
||||
|
||||
public SlidingWindowRateLimiter(int maxRequestsPerSecond) {
|
||||
this.semaphore = new Semaphore(maxRequestsPerSecond);
|
||||
int rate = 1000000 / maxRequestsPerSecond;
|
||||
scheduler.scheduleAtFixedRate(() -> {
|
||||
if (semaphore.availablePermits() < maxRequestsPerSecond) {
|
||||
semaphore.release(1);
|
||||
}
|
||||
}, 0, (1000 / maxRequestsPerSecond), TimeUnit.MILLISECONDS);
|
||||
}, rate, rate, TimeUnit.MICROSECONDS);
|
||||
}
|
||||
|
||||
public void aquire() throws InterruptedException {
|
||||
public void acquire() throws InterruptedException {
|
||||
semaphore.acquire();
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user