1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class CounterRateLimit implements RateLimit,Runnable {
private Integer limitCount = 10;
private AtomicInteger passCount;
private long period = 100;
private TimeUnit timeUnit;
private ScheduledExecutorService scheduledExecutorService;
public CounterRateLimit(Integer limitCount, long period, TimeUnit timeUnit){ this.limitCount = limitCount; this.period = period; this.timeUnit = timeUnit; this.passCount = new AtomicInteger(1); this.startResetTask(); }
public boolean canPass() throws BlockException { if(passCount.incrementAndGet() > limitCount){ throw new BlockException(); } return true; }
@Override public void run() { passCount.set(0); }
private void startResetTask(){ scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(this, 0, period, TimeUnit.MILLISECONDS); }
public static void main(String[] args) throws BlockException { CounterRateLimit counterRateLimit = new CounterRateLimit(10, 1000, TimeUnit.MILLISECONDS); for (int i = 0; i < 10000; i++){ if(counterRateLimit.canPass()){ System.out.println("通过第【" + i + "】个请求"); Thread.sleep(10); } } } }
|