实际工作中有这种需求:
某个接口被不同的外部ip大量访问,且每个IP的访问频率很高。为了节约后端服务器资源,于是想通过
RateLimiter令牌桶+自定义Aop注解来限制同一ip在单位时间内只能访问固定的次数,超过这个次数的请求被拦截掉。具体实现如下:
1、自定义Aop注解
package com.fancetech.tools.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.METHOD})
public @interface RequestLimitAnnotate {
/**
* 请求次数限制
*/
long requestLimitNum();
/**
* 限流的时间间隔,单位秒
*/
long timeInterval();
}
2、注解实现类
@Order(3)
@Aspect
@Component
@Slf4j
public class RequestLimitAop extends CBaseController {
/**
* 每秒产生的令牌数
*/
private double permitsPerSecond;
@Pointcut("@annotation(com.fancetech.tools.annotation.RequestLimitAnnotate)")
public void