日期:2014-05-17 浏览次数:20919 次
public class GetMsgServlet extends HttpServlet {
/**
* 用于存放请求IP以及时间戳数据
*/
private static final Map<String, Long> REQ_IP_CACHE =
new HashMap<String, Long>();
/**
* 限定的请求时间间隔, 5s
*/
private final static long TimeInterval = 5000;
// 你的其他代码
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
// 你预先要处理的一些代码.
boolean isFast = false;
String reqIp = req.getRemoteAddr();
Long timestamp = Long.valueOf(System.currentTimeMillis());
if ( REQ_IP_CACHE.contains(reqIp) ) {
Long storedTime = REQ_IP_CACHE.get(reqIp);
if ( (storedTime+TimeInterval) > timestamp ) {
isFast = true;
} else {
REQ_IP_CACHE.put(reqIp, timestamp);
}
} else {
REQ_IP_CACHE.put(reqIp, timestamp);
}
if ( !isFast ) {
// 你的业务代码
}
}
}