信号量机制实现服务并发限流

微服务架构常见并发限流原理:

1.计数器

    通过原子变量计算单位时间内的访问次数,如果超出某个阀值,则拒绝后续的请求,等到下一个单位时间再重新计数。

 

2.令牌筒

    令牌桶是一个流行的实现限流的技术方案,它通过一个线程在单位时间内生产固定数量的令牌,然后把令牌放入队列,没吃请求调用需要中桶中拿取一个令牌,拿到令牌后才有资格执行请求调用,否则只能等待拿到令牌再执行,或者直接丢弃。

 

3.信号量

举例实现:信号量机制实现服务并发限流

package com.app.main.architecture;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量机制实现并发限流
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/8/20
 * Time:下午7:33
 */
public class SemaphoreExample {
    private static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {

        final Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 200; i++) {

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        // 获得许可
                        semaphore.acquire();
                        // do something
                        Thread.sleep(300L);
                        // 释放许可
                        semaphore.release();
                        System.out.println("剩余许可: " + semaphore.availablePermits());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };

            executorService.execute(runnable);
        }

        executorService.shutdown();
    }

}

 

你可能感兴趣的:(架构)