@Component
@Aspect
public class RequestLimitAspect {
private static final Logger logger = LoggerFactory.getLogger(RequestLimitAspect.class);
@Resource
private RedisTemplate<String,Object> customRedisTemplate;
@Before("execution(public * com.toplion.apisix.dashboard.controller.*.*(..)) && @annotation(requestLimit)")
public void requestLimit(JoinPoint joinPoint, RequestLimit requestLimit) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert requestAttributes != null;
HttpServletRequest request = requestAttributes.getRequest();
// 获取ip
String ipAddress = HttpRequestUtil.getIpAddress(request);
// 获取url
String url = request.getRequestURL().toString();
// 拼接key值
String key = "limit_".concat(url).concat(ipAddress);
Long count = customRedisTemplate.opsForValue().increment(key, 1);
if(Objects.isNull(count)) {
throw BusinessException.L(ErrorCode.UPDATE_FAIL);
}
if(count == 1) {
// 设置过期时间
customRedisTemplate.expire(key,requestLimit.time(), TimeUnit.SECONDS);
}
// 访问次数过多
if(count > requestLimit.count()) {
logger.info("ip[{}],访问地址【{}】,访问频次过高",ipAddress,url);
throw BusinessException.L(ErrorCode.FREQUENT_VISITS);
}
}
}
请求接口限速
最新推荐文章于 2024-07-22 14:15:06 发布