上一篇 <<<服務的隔離、降級和熔斷
下一篇 >>>服務限流之滑動窗口計數(shù)
最簡單最容易的一種算法,比如我們要求某一個接口,1分鐘內(nèi)的請求不能超過10次,我們可以在開始時設置一個計數(shù)器,每次請求,該計數(shù)器+1;
如果該計數(shù)器的值大于10并且與第一次請求的時間間隔在1分鐘內(nèi),那么說明請求過多,如果該請求與第一次請求的時間間隔大于1分鐘,并且該計數(shù)器的值還在限流范圍內(nèi),那么重置該計數(shù)器。
缺陷:在臨界點會存在問題

/**
* 功能說明: 純手寫計數(shù)器方式<br>
*/
public class LimitService {
private int limtCount = 60;// 限制最大訪問的容量
AtomicInteger atomicInteger = new AtomicInteger(0); // 每秒鐘 實際請求的數(shù)量
private long start = System.currentTimeMillis();// 獲取當前系統(tǒng)時間
private int interval = 60;// 間隔時間60秒
public boolean acquire() {
long newTime = System.currentTimeMillis();
if (newTime > (start + interval)) {
// 判斷是否是一個周期
start = newTime;
atomicInteger.set(0); // 清理為0
return true;
}
atomicInteger.incrementAndGet();// i++;
return atomicInteger.get() <= limtCount;
}
static LimitService limitService = new LimitService();
public static void main(String[] args) {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
for (int i = 1; i < 100; i++) {
final int tempI = i;
newCachedThreadPool.execute(new Runnable() {
public void run() {
if (limitService.acquire()) {
System.out.println("你沒有被限流,可以正常訪問邏輯 i:" + tempI);
} else {
System.out.println("你已經(jīng)被限流呢 i:" + tempI);
}
}
});
}
}
}
推薦閱讀:
<<<高并發(fā)架構的整體思路
<<<一個網(wǎng)站訪問慢的真正原因
<<<高并發(fā)情況下,接口的代碼會存在哪些問題
<<<壓縮靜態(tài)資源減少帶寬傳輸?shù)姆绞?/a>
<<<動靜分離架構模式
<<<緩存策略匯總
<<<后端服務的雪崩效應及解決思路
<<<服務的隔離、降級和熔斷
<<<服務限流之滑動窗口計數(shù)
<<<服務限流之令牌桶算法
<<<服務限流之漏桶算法
<<<漏桶算法和令牌桶算法的區(qū)別
<<<自定義封裝限流算法
<<<應用級限流
<<<接入層限流