在Java中實現接口限流可以使用以下幾種方式:
import java.util.concurrent.ConcurrentHashMap;
public class RateLimiter {
private static ConcurrentHashMap<String, Integer> counters = new ConcurrentHashMap<>();
private static final int MAX_REQUESTS = 100; // 設定的閾值
public static boolean allowRequest(String interfaceName) {
counters.putIfAbsent(interfaceName, 0);
int count = counters.get(interfaceName);
if (count >= MAX_REQUESTS) {
return false;
}
counters.put(interfaceName, count + 1);
return true;
}
public static void main(String[] args) {
String interfaceName = "interface1";
for (int i = 0; i < 110; i++) {
if (allowRequest(interfaceName)) {
System.out.println("Allow request for interface: " + interfaceName);
} else {
System.out.println("Reject request for interface: " + interfaceName);
}
}
}
}
import java.util.ArrayDeque;
import java.util.Queue;
public class RateLimiter {
private static Queue<Long> timestamps = new ArrayDeque<>();
private static final int WINDOW_SIZE = 1000; // 窗口大小,單位為毫秒
private static final int MAX_REQUESTS = 100; // 設定的閾值
public static boolean allowRequest() {
long now = System.currentTimeMillis();
timestamps.offer(now);
while (!timestamps.isEmpty() && now - timestamps.peek() > WINDOW_SIZE) {
timestamps.poll();
}
return timestamps.size() <= MAX_REQUESTS;
}
public static void main(String[] args) {
for (int i = 0; i < 110; i++) {
if (allowRequest()) {
System.out.println("Allow request");
} else {
System.out.println("Reject request");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.concurrent.Semaphore;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RateLimiter {
private static Semaphore tokens = new Semaphore(10); // 初始令牌數量
private static final int RATE = 1; // 產生令牌的速率,單位為個/秒
public static boolean allowRequest() {
return tokens.tryAcquire();
}
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(() -> {
int availableTokens = tokens.availablePermits();
if (availableTokens < RATE) {
tokens.release(RATE - availableTokens);
}
}, 0, 1, TimeUnit.SECONDS);
for (int i = 0; i < 20; i++) {
if (allowRequest()) {
System.out.println("Allow request");
} else {
System.out.println("Reject request");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
以上是幾種常見的Java接口限流的實現方式,可以根據實際需求選擇適合的方式。