# Guava教程-RateLimiter

## 简介

RateLimiter类定义如下：

com.google.common.util.concurrent.RateLimiter

@Beta
public abstract class RateLimiter
extends Object

Guava Docs关于RateLimiter介绍如下：

A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each acquire() blocks if necessary until a permit is available, and then takes it. Once acquired, permits need not be released.

Rate limiters are often used to restrict the rate at which some physical or logical resource is accessed. This is in contrast to Semaphore which restricts the number of concurrent accesses instead of the rate (note though that concurrency and rate are closely related, e.g. see Little’s Law).

A RateLimiter is defined primarily by the rate at which permits are issued. Absent additional configuration, permits will be distributed at a fixed rate, defined in terms of permits per second. Permits will be distributed smoothly, with the delay between individual permits being adjusted to ensure that the configured rate is maintained.

It is possible to configure a RateLimiter to have a warmup period during which time the permits issued each second steadily increases until it hits the stable rate.

RateLimiter使用的是一种叫令牌桶的流控算法，RateLimiter会按照一定的频率往桶里扔令牌，线程拿到令牌才能执行，比如你希望自己的应用程序QPS不要超过1000，那么RateLimiter设置1000的速率后，就会每秒往桶里扔1000个令牌。

## 用法

final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second"
rateLimiter.acquire(); // may wait
}
}


final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second
void submitPacket(byte[] packet) {
rateLimiter.acquire(packet.length);
networkService.send(packet);
}

It is important to note that the number of permits requested never affect the throttling of the request itself (an invocation to acquire(1) and an invocation to acquire(1000) will result in exactly the same throttling, if any), but it affects the throttling of the next request. I.e., if an expensive task arrives at an idle RateLimiter, it will be granted immediately, but it is the next request that will experience extra throttling, thus paying for the cost of the expensive task.

Note: RateLimiter does not provide fairness guarantees.

## 应用


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

public class ApiCallDemo {

private int permitsPerSecond = 55; //每秒55个许可

public static void main(String[] args) {

new ApiCallDemo().call();
}

private void call() {

final RateLimiter rateLimiter = RateLimiter.create(permitsPerSecond);
for (int i=0; i<threadNum; i++) {
}

executor.shutdown();
}
}

private RateLimiter rateLimiter;
private boolean runing = true;
this.rateLimiter = rateLimiter;
}

@Override
public void run() {

while(runing){
rateLimiter.acquire(); // may wait
getData();
}
}

/**模拟调用合作伙伴API接口*/
private void getData(){