Java限流策
計數器限流算法
計數器限流算法也是比較常用的,主要用來限制總并發數,比如數據庫連接池大小、線程池大小、程序訪問并發數等都是使用計數器算法。
public class CountRateLimiterDemo1 {private static AtomicInteger count = new AtomicInteger(0);public static void exec() {if (count.get() >= 5) {System.out.println("請求用戶過多,請稍后在試!"+System.currentTimeMillis()/1000);} else {count.incrementAndGet();try {//處理核心邏輯TimeUnit.SECONDS.sleep(1);System.out.println("--"+System.currentTimeMillis()/1000);} catch (InterruptedException e) {e.printStackTrace();} finally {count.decrementAndGet();}}} }使用AomicInteger來進行統計當前正在并發執行的次數,如果超過域值就簡單粗暴的直接響應給用戶,說明系統繁忙,請稍后再試或其它跟業務相關的信息。
弊端:使用 AomicInteger 簡單粗暴超過域值就拒絕請求,可能只是瞬時的請求量高,也會拒絕請求。
使用計數器限流示例2
public class CountRateLimiterDemo2 {private static Semaphore semphore = new Semaphore(5);public static void exec() {if(semphore.getQueueLength()>100){System.out.println("當前等待排隊的任務數大于100,請稍候再試...");}try {semphore.acquire();// 處理核心邏輯TimeUnit.SECONDS.sleep(1);System.out.println("--" + System.currentTimeMillis() / 1000);} catch (InterruptedException e) {e.printStackTrace();} finally {semphore.release();}} }使用Semaphore信號量來控制并發執行的次數,如果超過域值信號量,則進入阻塞隊列中排隊等待獲取信號量進行執行。如果阻塞隊列中排隊的請求過多超出系統處理能力,則可以在拒絕請求。
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
- 上一篇: 数据结构2017
- 下一篇: EJB(Enterprise Java