久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

java接口限流如何實現(xiàn)

142次閱讀
沒有評論

共計 2497 個字符,預(yù)計需要花費(fèi) 7 分鐘才能閱讀完成。

在 Java 中實現(xiàn)接口限流可以使用以下幾種方式:

  1. 計數(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);
            }
        }
    }
}
  1. 滑動窗口:使用一個固定長度的時間窗口,統(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();
            }
        }
    }
}
  1. 令牌桶:使用一個固定速率產(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ì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-16發(fā)表,共計2497字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 东阿县| 神农架林区| 乌拉特中旗| 莎车县| 横峰县| 铅山县| 平湖市| 漠河县| 永年县| 观塘区| 同心县| 德州市| 新沂市| 西昌市| 合江县| 潞城市| 布拖县| 汉沽区| 莱阳市| 甘肃省| 金寨县| 佛山市| 新晃| 乌兰察布市| 忻城县| 合作市| 板桥市| 耿马| 泰来县| 武川县| 商都县| 普兰县| 尖扎县| 北流市| 三门峡市| 广东省| 桑日县| 获嘉县| 绥化市| 华宁县| 舟山市|