限流拦截器辅助类,用于存储每个请求的并发访问数:
/**
* @date 2017年8月4日
*/
package com.wedoctor.health.card.cloud.api.home.interceptor;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 限流拦截器辅助类,用于存储每个请求的访问数
* @author wangshuai
* @date 2017年8月4日
*/
public class AccessCounts {
/**
* 统计KEY值
*/
public static final String URL = "AccessCounts.URL";
/**
* 并发计数
*/
private ConcurrentHashMap
拦截器代码:
/**
* @date 2017年8月4日
*/
package com.wedoctor.health.card.cloud.api.home.interceptor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 限流拦截器
*
* @author wangshuai
* @date 2017年8月4日
*/
public class InServiceAccessInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = Logger.getLogger(InServiceAccessInterceptor.class);
/**
* 配置信息
*/
private ConcurrentHashMap config = new ConcurrentHashMap();
/**
* 默认的限制次数
*/
private int defaultLimit = 100;
/**
* 配置文件的URL
*/
private String configUrl = null;
/**
* 加载配置文件的频率
*/
private int loadInterval = 1, loadDelay = 5;
/**
* 是否合法
*/
private boolean valid;
/**
* 拦截器构造函数, 传入的参数在xml中配置
* @param defaultLimit
* @param configUrl
* @param loadInterval
* @param loadDelay
* @param valid
*/
public InServiceAccessInterceptor(int defaultLimit, String configUrl, int loadInterval, int loadDelay, boolean valid) {
this.defaultLimit = defaultLimit;
this.configUrl = configUrl;
this.loadInterval = loadInterval;
this.loadDelay = loadDelay;
this.valid = valid;
if (valid) {
task();
}
}
/**
* 拦截器逻辑
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (valid) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String callpath = handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "."
+ handlerMethod.getMethod().getName();
System.out.println(callpath);
int counter = AccessCounts.getInstance().get(callpath);
boolean limit = limit(callpath, counter);
if (limit) {
throw new IllegalAccessException("调用次数超出限制." + callpath + "=" + counter);
}
MDC.put(AccessCounts.CALLPATH, callpath);
AccessCounts.getInstance().incrementAndGet(callpath);
}
}
return true;
}
/**
* 每次执行完后,清除计数,实现限制同一个API同时调用的次数
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (valid) {
Object callpath = MDC.get(AccessCounts.CALLPATH);
if (null != callpath) {
AccessCounts.getInstance().decrementAndGet(callpath);
}
MDC.remove(AccessCounts.CALLPATH);
}
}
/**
*
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
/**
* 判断是否超出限制次数
* @date 2017年8月4日
* @author wangshuai
* @param callpath
* @param counter
* @return
*/
private boolean limit(String callpath, int counter) {
//每次都从配置中读取限制的次数
Integer obj = config.get(callpath);
int limit = defaultLimit;
if (obj != null) {
limit = obj.intValue();
}
System.out.println("check callpath:" + callpath + " limit:" + limit + " counter:" + counter);
if (logger.isDebugEnabled()) {
logger.debug("check callpath:" + callpath + " limit:" + limit + " counter:" + counter);
}
if (counter >= limit) {
System.out.println("the call[" + callpath + "] is over limit:" + limit + " counter:" + counter);
logger.warn("the call[" + callpath + "] is over limit:" + limit + " counter:" + counter);
return true;
}
return false;
}
/**
* 定时更新拦截器配置
* @date 2017年8月4日
* @author wangshuai
*/
public void task() {
TimerTask task = new TimerTask() {
@Override
public void run() {
if (null == configUrl)
return;
String text = sendGet(configUrl, null);
logger.info("load config:" + text);
if (null == text || "".equals(text.trim()))
return;
text = text.replaceAll("[\\{\\}\"\n]", "");
config.clear();
for (String line : text.split(",")) {
String fields[] = line.split(":");
if (fields.length < 2)
continue;
try {
config.put(fields[0].trim(), Integer.valueOf(fields[1].trim()));
} catch (Exception e) {
logger.error("load config fail.", e);
}
}
}
};
Timer timer = new Timer();
long delay = 1000 * loadDelay;
long intevalPeriod = 1000 * loadInterval;
// schedules the task to be run in an interval
logger.info("Task setting delay:" + delay + " intevalPeriod:" + intevalPeriod);
timer.scheduleAtFixedRate(task, delay, intevalPeriod);
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("AccessCounts status:" + AccessCounts.getInstance().status());
}
}
}).start();
}
/**
* 从url中获取配置字符串
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + (param == null ? "" : "?" + param);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
/*
* Map> map = connection.getHeaderFields(); for
* (String key : map.keySet()) { System.out.println(key + "--->" +
* map.get(key)); }
*/
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("request url fail=" + url, e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
}
}
return result;
}
}
xml配置:
http://localhost/web.limit配置文件内容:
{"IndexController.index":500,
"ProductController.searchProducts":500
}