作者:一粟
实现一个流控程序。控制客户端每秒调用某个远程服务不超过N次,客户端是会多线程并发调用,需要一个轻量简洁的实现,大家看看下面的一个实现,然后可以自己写一个实现。
01 | import java.util.Date; |
02 |
03 | import java.util.concurrent.ExecutorService; |
04 |
05 | import java.util.concurrent.Executors; |
06 |
07 | import java.util.concurrent.Semaphore; |
08 |
09 | import java.util.concurrent.TimeUnit; |
10 |
11 | public class Test { |
12 |
13 | final static int MAX_QPS = 10 ; |
14 |
15 | final static Semaphore semaphore = new Semaphore(MAX_QPS); |
16 |
17 | public static void main (String ... args) throws Exception { |
18 |
19 | Executors.newScheduledThreadPool( 1 ).scheduleAtFixedRate( new Runnable() { |
20 |
21 | @Override |
22 |
23 | public void run() { |
24 |
25 | semaphore.release(MAX_QPS/ 2 ); |
26 |
27 | } |
28 |
29 | }, 1000 , 500 , TimeUnit.MILLISECONDS); |
30 |
31 | //lots of concurrent calls:100 * 1000 |
32 | ExecutorService pool = Executors.newFixedThreadPool( 100 ); |
33 |
34 | for ( int i= 100 ;i> 0 ;i--) { |
35 |
36 | final int x = i; |
37 |
38 | pool.submit( new Runnable() { |
39 |
40 | @Override |
41 |
42 | public void run() { |
43 |
44 | for ( int j= 1000 ;j> 0 ;j--) { |
45 |
46 | semaphore.acquireUninterruptibly( 1 ); |
47 | remoteCall(x, j); |
48 |
49 | } |
50 |
51 | } |
52 |
53 | }); |
54 |
55 | } |
56 |
57 | pool.shutdown(); |
58 |
59 | pool.awaitTermination( 1 , TimeUnit.HOURS); |
60 |
61 | System.out.println( "DONE" ); |
62 | } |
63 |
64 | private static void remoteCall( int i, int j) { |
65 | System.out.println(String.format( "%s - %s: %d %d" , new Date(), |
66 | Thread.currentThread(), i, j)); |
67 | } |
68 |
69 | } |