RateLimiter:速率限制器
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()");
}
}
}
}