扰扰博客

java请求频次控制

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());
            }
        }
    }
}

 

posted @ 2024-11-15 14:18  扰扰  阅读(48)  评论(0)    收藏  举报