高并发请求下的限流控制

import com.google.common.util.concurrent.RateLimiter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * guava RateLimiter限制速率,采用令牌桶算法来实现
 * 知识扩充点1:Semaphore-控制对资源访问的线程数量;RateLimiter-控制对资源访问的速率,每秒多少个
 * 知识扩充点2:限流算法:漏桶算法、令牌桶算法
 */
public class LimitReq {

    public static void main(String[] args) {

        List requests = new ArrayList<>();
        for(int i = 0 ;i < 10000; i++){
            requests.add(new HttqReq(i));
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        //速率是每秒100个许可
        RateLimiter rateLimiter = RateLimiter.create(100);
        for(Runnable request : requests){
            //开启限流
            rateLimiter.acquire();
            executorService.submit(request);
        }

    }

    /**
     * 模拟请求的线程
     */
    static class HttqReq implements Runnable{
        int cnt;
        HttqReq(int cnt){
            this.cnt = cnt;
        }
        @Override
        public void run() {
            System.out.println(cnt+"请求");
        }
    }
}
maven pom dependency

    com.google.guava
    guava
    18.0

 

转载于:https://my.oschina.net/u/2443971/blog/3060598

你可能感兴趣的:(高并发请求下的限流控制)