引言
显示中存在恶意ip频繁请求情况,本文通过自定义注解+拦截器实现限制ip访问的频率
实现
1. 添加pom依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
2. 添加自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
* 允许访问的最大次数
*/
int count() default Integer.MAX_VALUE;
/**
* 时间段,单位为毫秒,默认值一分钟
*/
long time() default 60000;
}
3. 添加自定义异常
public class RequestLimitException extends NestedRuntimeException {
public RequestLimitException(){
super("HTTP请求超出设定的限制");
}
public RequestLimitException(String msg) {
super(msg);
}
}
4. 添加自定义拦截器
interceptor
@Slf4j
@Aspect
@Component
public class RequestLimitInterceptor {
@Before("within(@org.springframework.web.bind.annotation.RequestMapping * || @javax.ws.rs.Path *) && @annotation(limit)")
public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
try {
// 获取 HttpServletRequest
Object[] args = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < args.length; i++) {
if (<