需求:实现一个流控程序。控制客户端每秒调用某个远程服务不超过N次,客户端是会多线程并发调用。
代码:
/**
* @author wzx
* @time 2018/2/9
*/
public class RateLimiterTest {
final static int MAX_QPS = 10;
final static Semaphore semaphore = new Semaphore(MAX_QPS);
public static void main(String[] args) throws InterruptedException {
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
semaphore.release(MAX_QPS / 2);
}
}, 1, 1, TimeUnit.SECONDS);
ExecutorService service = Executors.newFixedThreadPool(100);
for (int i = 100; i > 0; i--) {
final int x = i;
service.submit(new Runnable() {
@Override
public void run() {
for (int j = 1000; j > 0; j--) {
semaphore.acquireUninterruptibly(1);
remoteCall(x, j);
}
}
});
}
service.shutdown();
service.awaitTermination(1, TimeUnit.HOURS);
}
private static void remoteCall(int i, int j) {
System.out.println(String.format("%s - %s: %d %d", new Date(), Thread.currentThread(), i, j));
}
}
输出结果:
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-7,5,main]: 94 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-9,5,main]: 92 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-5,5,main]: 96 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-1,5,main]: 100 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-8,5,main]: 93 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-2,5,main]: 99 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-4,5,main]: 97 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-3,5,main]: 98 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-10,5,main]: 91 1000
Fri Feb 09 12:18:54 CST 2018 - Thread[pool-2-thread-6,5,main]: 95 1000
100
Fri Feb 09 12:18:55 CST 2018 - Thread[pool-2-thread-8,5,main]: 93 999
Fri Feb 09 12:18:55 CST 2018 - Thread[pool-2-thread-9,5,main]: 92 999
Fri Feb 09 12:18:55 CST 2018 - Thread[pool-2-thread-1,5,main]: 100 999
Fri Feb 09 12:18:55 CST 2018 - Thread[pool-2-thread-5,5,main]: 96 999
Fri Feb 09 12:18:55 CST 2018 - Thread[pool-2-thread-7,5,main]: 94 999
100
Fri Feb 09 12:18:56 CST 2018 - Thread[pool-2-thread-10,5,main]: 91 999
Fri Feb 09 12:18:56 CST 2018 - Thread[pool-2-thread-2,5,main]: 99 999
Fri Feb 09 12:18:56 CST 2018 - Thread[pool-2-thread-3,5,main]: 98 999
Fri Feb 09 12:18:56 CST 2018 - Thread[pool-2-thread-4,5,main]: 97 999
Fri Feb 09 12:18:56 CST 2018 - Thread[pool-2-thread-6,5,main]: 95 999