简单的API限流接口

简单的API限流接口,主要用于控制某个IP指定时间段内,可访问指定资源多少次或类似的场景from江巅

package jbs.erp.module.cashier.util;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * api限流
 * @author Administrator
 *
 */
public class ApiLimit {

/**
* 一个IP一天只能跑100个
*/
private static final int one_ip_one_day_limit_count=100;

private static Map ipLimit = new HashMap();



public static boolean limit(String ip) {
if(null == ip || ip.equals("")) {
return true;
}
if(!ipLimit.containsKey(ip)) {
ipLimit.put(ip,new IpLimit(new AtomicInteger(0), System.currentTimeMillis()));
}

IpLimit il= ipLimit.get(ip);
if(System.currentTimeMillis()-il.getTime()>24*60*60*1000) {
il.getCounter().set(0);
il.setTime(System.currentTimeMillis());
}

if(il.getCounter().incrementAndGet()>one_ip_one_day_limit_count)
{
return false;
}


return true;
}
}


class IpLimit {

private AtomicInteger counter;
private Long time;
protected IpLimit(AtomicInteger counter,Long updateTime) {
this.counter=counter;
this.time=updateTime;
}
public AtomicInteger getCounter() {
return counter;
}
public void setCounter(AtomicInteger counter) {
this.counter = counter;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
 

}

 

 

你可能感兴趣的:(简单的API限流接口)