Guava的RateLimiter限流

引用

com.google.guava
guava
18.0

简单demo

public class RateLimiterTest {

    @Test
    public void test1() {
        RateLimiter limiter = RateLimiter.create(2.0); //每秒不超过2个任务被提交
        for(int i=0;i<12;i++){
            limiter.acquire();//请求RateLimiter, 超过permits会被阻塞
            System.out.println(System.currentTimeMillis());//500ms
        }
    }

    @Test
    public void test2() throws Exception{
        RateLimiter limiter = RateLimiter.create(4.0);
        for(int i=0;i<10;i++){
            Thread.sleep(100);
            if(limiter.tryAcquire()){ //未请求到limiter则立即返回false
                System.out.println("doSomething()");
            }else{
                System.out.println("doSomethingElse()");
            }
        }
    }

}

RateLimiter 是线程安全的

你可能感兴趣的:(Guava的RateLimiter限流)