限制同一IP一段时间内访问次数

此方式简单粗暴…
项目中有个发邮件功能,是网站暴露给用户的一个反馈意见的邮件入口,由于省事未使用redis或漏斗或平滑限流.只是个简单粗暴的限流,根据实际情况使用.

private CopyOnWriteArrayList<ConcurrentHashMap<String,Long>> ipList = new CopyOnWriteArrayList<>();

@RequestMapping(value = "/sendMsg.jspx")
	public void sendMsg(HttpServletRequest request,HttpServletResponse response) throws JSONException {
		try {
			//限制访问频率
			String userIp = request.getRemoteAddr();
			ConcurrentHashMap<String,Long> ipMap = new ConcurrentHashMap<>();
			if(ipList!=null && !ipList.isEmpty()){
				for(ConcurrentHashMap<String,Long> myMap : ipList) {
					if(myMap.get(userIp) != null) {
						//同一IP 3秒内只能提交一次
						if(System.currentTimeMillis() - myMap.get(userIp) < 3 * 1000){
							myMap.put(userIp,System.currentTimeMillis());
							ResponseUtils.renderJson(response, "提交过于频繁!");
						}
					}
				}
				if(ipList.size()==10) {
					//放满10次请求 清空一次
					ipList.clear();
				}
			}
			ipMap.put(userIp,System.currentTimeMillis());
			ipList.add(ipMap);
			//发邮件--实际业务
			sendEmail.sendEmil();
			ResponseUtils.renderJson(response, "提交成功!");
		} catch (NumberFormatException e) {
			ResponseUtils.renderJson(response, "提交失败!");
			e.printStackTrace();
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_29312259/article/details/84704402
今日推荐