限流模式【其他模式】

限流模式

@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);
    }
}
原文地址:https://www.cnblogs.com/zhuxudong/p/10225650.html