1. 程式人生 > >限流模式【其他模式】

限流模式【其他模式】

限流模式

@Slf4j
public class Throttling {
    /**
     *  限流模式:
     * Ensure that a given client is not able to access service resources
     * more than the assigned limit.
     *  確保給定的客戶端不能訪問超出限制的服務資源。
     */
    @Test
    public void all() throws InterruptedException {
        // 每秒最多可獲取 5 個許可的限流器
        final RateLimiter limiter = RateLimiter.create(5);
        final ExecutorService executorService = Executors.newCachedThreadPool();
        final CyclicBarrier barrier = new CyclicBarrier(20);
        IntStream.range(0, 20).forEach(val -> {
            executorService.submit(() -> {
                try {
                    // 讓 20 個執行緒在同一時刻競爭
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    log.error("", e);
                }

                // 嘗試在 1 秒內獲取一個許可
                if (limiter.tryAcquire(1, TimeUnit.SECONDS)) {
                    log.info("acquire successfully for thread {}", Thread.currentThread().getName());
                } else {
                    log.info("acquire failed for thread {}", Thread.currentThread().getName());
                }
            });
        });
        executorService.awaitTermination(2, TimeUnit.SECONDS);
    }
}