参考博文:根据IP限制指定时间内访问接口的次数
/**
* 请求次数限制:一分钟内一个IP只能请求指定次数
* 1.检查IP是否存在(一分钟内是否登录过),如果不存在,设置key和value 过期时间1分钟,
* 存在,value+1并且设置过期时间,value大于指定次数,返回请求超过限制
*
* key为ip ,value 为调用次数
*
* @param request
* @return
*/
public boolean isAllowIncrement(HttpServletRequest request,Integer id) {
boolean isAllowed = true;
// 获取请求IP
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
ip = "" + request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
ip = "" + request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
ip = "" + request.getRemoteAddr();
}
// 前缀+id+ip构成key
String key = prefix+id+ip;
//检查key是否存在,返回boolean值
boolean flag = stringRedisTemplate.hasKey(key);
if (flag) {
// 调用次数+1
stringRedisTemplate.boundValueOps(key).increment(1);
// 设置过期时间
stringRedisTemplate.expire(ip, EXPIRATIONTIME_SECONDS,TimeUnit.SECONDS);
String sumVal = stringRedisTemplate.opsForValue().get(key);
int sum = Integer.valueOf(sumVal);
if (sum > 2) {
System.out.println("第" + sum + "次请求,浏览次数不能继续增加!");
isAllowed = false;
return isAllowed;
}
}else {
// 第一次调用,所以value(调用次数)设置为1
stringRedisTemplate.opsForValue().set(key, "1",EXPIRATIONTIME_SECONDS,TimeUnit.SECONDS);
}
String num = stringRedisTemplate.opsForValue().get(key);
System.out.println("第"+num+"次请求,请求成功!");
return isAllowed;
}