@Aspect
@Component
@Slf4j
public class RequestLimitContract {
private static final Logger logger = LoggerFactory.getLogger("requestLimitLogger");
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ObjectMapper objectMapper;
@Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
public void requestLimit(final JoinPoint joinPoint , RequestLimit limit) throws RequestLimitException {
try {
LoginForm loginForm = new LoginForm();
Object[] args = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest) {
request = (HttpServletRequest) args[i];
break;
} else if (args[i] instanceof LoginForm) {
loginForm = (LoginForm) args[i];
}
}
if (request == null) {
throw new RequestLimitException("方法中缺失HttpServletRequest参数");
}
//获取请求中的ip与url链接参数 用于拼接key存放redis中
String ip = loginForm.getIpAddress();
String url = request.getRequestURL().toString();
Long interview_time = new Date().getTime();
String key = "req_limit_".concat(url).concat("---").concat(ip);
System.err.println("准备保存在redis中的数据为-->");
Map<String, Long> form = new HashMap<>();
form.put("size", 1L);
form.put("saveRedisTime", interview_time);
if (redisTemplate.opsForValue().get(key) == null) {
System.err.println(form);
redisTemplate.opsForValue().set(key, form);
} else {
//用于进行ip访问的计数
Map<String, Long> result = (Map<String, Long>) redisTemplate.opsForValue().get(key);
System.err.println("从redis取到的数据(内部)");
System.out.println(result);
assert result != null;
result.put("size", result.get("size") + 1);
redisTemplate.opsForValue().set(key, result);
if (result.get("size") > 10) {
logger.info("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
throw new RequestLimitException();
}
// 如果访问次数小于 10 次,那么一分钟过后就直接删除这个节点
if (result.get("size") <= limit.count()) {
//创建一个定时器
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
redisTemplate.delete(key);
}
};
//这个定时器设定在time规定的时间之后会执行上面的remove方法,也就是说在这个时间后它可以重新访问
timer.schedule(timerTask, limit.time());
}
}
}catch (RequestLimitException e){
throw e;
}catch (Exception e){
logger.error("发生异常",e);
}
}
}
|