共計 2497 個字符,預(yù)計需要花費(fèi) 7 分鐘才能閱讀完成。
在 Java 中實現(xiàn)接口限流可以使用以下幾種方式:
- 計數(shù)器:維護(hù)一個計數(shù)器來統(tǒng)計每個接口的請求數(shù)量,當(dāng)請求數(shù)量超過設(shè)定的閾值時,拒絕后續(xù)的請求。這可以使用并發(fā)容器如 ConcurrentHashMap 來實現(xiàn),其中接口作為 key,計數(shù)器作為 value。
import java.util.concurrent.ConcurrentHashMap;
public class RateLimiter {private static ConcurrentHashMap<String, Integer> counters = new ConcurrentHashMap<>();
private static final int MAX_REQUESTS = 100; // 設(shè)定的閾值
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);
}
}
}
}
- 滑動窗口:使用一個固定長度的時間窗口,統(tǒng)計窗口內(nèi)的請求數(shù)量。當(dāng)請求數(shù)量超過設(shè)定的閾值時,拒絕后續(xù)的請求。這可以使用隊列或數(shù)組來保存請求的時間戳,并通過計算窗口內(nèi)的請求數(shù)量來進(jìn)行限流。
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; // 設(shè)定的閾值
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();
}
}
}
}
- 令牌桶:使用一個固定速率產(chǎn)生令牌,每個請求需要獲取一個令牌才能通過。當(dāng)令牌數(shù)量不足時,拒絕后續(xù)的請求。這可以使用 ScheduledExecutorService 來定時產(chǎn)生令牌,并使用 Semaphore 來控制令牌的獲取。
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); // 初始令牌數(shù)量
private static final int RATE = 1; // 產(chǎn)生令牌的速率,單位為個 / 秒
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 接口限流的實現(xiàn)方式,可以根據(jù)實際需求選擇適合的方式。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2023-12-16