两种白名单限流方案
1、redis lua方案
创建注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Limit {
// 资源名称,用于描述接口功能
String name() default "";
// 资源 key
String key() default "";
// key 前缀
String prefix() default "";
// 时间单位秒
int period();
// 限制单位时间访问的次数
int count();
// 限制类型
LimitType limitType() default LimitType.CUSTOMER;
}
编写AOP拦截类
@Slf4j
@Aspect
@Component
public class LimitAspect {
@Autowired
@Qualifier("jacksonRedisTemplate")
private RedisTemplate<String,Object> redisTemplate;
@Pointcut("@annotation(com.xx.common.annotation.Limit)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
Limit limitAnnotation = method.getAnnotation(Limit.class);
LimitType limitType = limitAnnotation.limitType();
String name = limitAnnotation.name();
String key;
String ip = IpUtil.getIpAddr(request);
int limitPeriod = limitAnnotation.period