制御リソースの毎秒のアクセス回数の実現

3653 ワード

普段インターフェースの開発をする時、インターフェースのアクセス頻度を制御する必要がある必要があるかもしれません。例えば、あるインターフェースは毎秒最大100回までアクセスできます。私達は同時ツールの種類のSemaphoreによって実現できます。以下はコード例です。
public class TPSLimiter {

    private Semaphore semaphore = null;

    public OPSLimiter(int maxOps) {
        if (maxOps < 1) {
            throw new IllegalArgumentException("maxOps must be greater than zero");
        }
        this.semaphore = new Semaphore(maxOps);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() ->
                //            ,        
                semaphore.release(maxOps), 1000, 1000, TimeUnit.MILLISECONDS);
    }

    /**
     *             ,     ops       
     */
    public void await() {
        semaphore.acquireUninterruptibly(1);
    }
}
以下はテストコードです。
public class TPSLimiterTest {
    static AtomicInteger at = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        TPSLimiter limiter = new TPSLimiter(100);

        new Thread(() -> {
            while (true) {
                //       AtomicInteger    
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(at.get());
            }
        }).start();

        //   100    AtomicIntegerfor (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    //           await  ,     ops      
                    limiter.await();
                    at.incrementAndGet();
                }
            }).start();
        }
    }
}
このブログは本人のメモです。皆様の参考になるだけです。ありがとうございます。