bug修复

This commit is contained in:
2025-02-05 11:28:50 +08:00
parent 0b861f0e21
commit 7892c0f5cc
21 changed files with 324 additions and 95 deletions

View File

@ -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();
}
}

View File

@ -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();
}