api call count limit

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ApiInvokeLimit {

private volatile long nextTime = 0;
private final long invetime = 5;
private final int maxCount = 2000;
private ConcurrentHashMap<String,AtomicInteger> appKey2InvokeCounts ;

public boolean isPass(String appkey){

long currentTime = System.currentTimeMillis();
ConcurrentHashMap<String,AtomicInteger> appKey2InvokeCount =  appKey2InvokeCounts;
if(currentTime > nextTime){
update(currentTime);

appKey2InvokeCount =  appKey2InvokeCounts;
}

AtomicInteger c = appKey2InvokeCount.get(appkey);
if(c == null){
c = appKey2InvokeCount.putIfAbsent(appkey, new AtomicInteger(0));
}
return c.get() > maxCount ? false : c.incrementAndGet() <= maxCount;
}


private synchronized void update(long currentTime) {
if(currentTime <= nextTime)
return ;
appKey2InvokeCounts = new ConcurrentHashMap<String,AtomicInteger>();
nextTime = currentTime + invetime;
}

public static void main(String[] args) {

ApiInvokeLimit d = new ApiInvokeLimit();
for (int i = 0; i < 2001; i++) {
System.out.println(d.isPass("pdy"));
}
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326225832&siteId=291194637
Recommended