java請求頻次控制

扰扰發表於2024-11-15

1、新增工具類

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 頻次呼叫控制類
 */
public class RateLimiterUtil {
    private final AtomicInteger sum;
    private final int maxRequests;
    private long period = 1000; // 1秒
    private long lastTime = System.currentTimeMillis();

    /**
     * 建構函式,初始化最大請求速率和週期
     * @param maxRequests 單位週期內可接受的最大呼叫次數
     * @param period 預設1秒
     */
    public RateLimiterUtil(int maxRequests, Long period)  {
        this.maxRequests = maxRequests;
        this.period=period;
        this.sum = new AtomicInteger(maxRequests);
    }

    /**
     * 獲取許可,如果超過最大速率則等待
     * @throws InterruptedException
     */
    public void acquire() throws InterruptedException {
        long currentTime = System.currentTimeMillis();
        long elapsed = currentTime - lastTime;
        if (elapsed >= period) {
            lastTime = currentTime;
            sum.set(maxRequests);
        }
        int i = sum.decrementAndGet();
        if(i<=0){
            Thread.sleep(period);
        }
    }

    public static void main(String[] args) {
        RateLimiterUtil rateLimiter = new RateLimiterUtil(10,1000l);

        for (int i = 0; i < 1000; i++) {
            try {
                rateLimiter.acquire();
                // 模擬傳送HTTP請求
                System.out.println("Sending HTTP request: " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Thread interrupted: " + e.getMessage());
            }
        }
    }
}

相關文章