Javaインターフェースでレートリミットをどのように実装するか

Javaでインターフェースの制限を行う方法は次のとおりです。

  1. カウント機能: 各インターフェースへのリクエスト数をカウントするカウンターを維持し、リクエスト数が所定の閾値を超えた場合は以降のリクエストを拒否します。これは、ConcurrentHashMap などの並行コンテナを使用して実装できます。このコンテナでは、インターフェースがキーとなり、カウンターが値となります。
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);
            }
        }
    }
}
  1. 一定時間の範囲内におけるリクエスト量をカウントする、固定長の時間ウィンドウを使用します。リクエスト量が規定された閾値を超えると、後続のリクエストを拒否します。これには、リクエストのタイムスタンプを保存するためのキューまたは配列を使用して、ウィンドウ内でのリクエスト数を計算することで、制限を設けることができます。
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();
            }
        }
    }
}
  1. トークンバケット:一定の速度でトークンを生成し、各リクエストは通過するためにトークンを取得する必要がある。トークン数が不足している場合は、後続のリクエストを拒否する。ScheduledExecutorServiceを使用してトークンの定時生成を行い、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); // 初始令牌数量
    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インターフェースの限流実装方法をいくつか検討し、実際のニーズに応じて適切な方法を選択できます。

bannerAds