赞
踩
因为在面对大并发大流量的请求时,突发情况下,大量的请求会将系统整垮,造成响应失败超时等状况。那为了防止出现这种情况最常见的解决方案之一就是限流,当请求达到一定的并发数或速率,就进行等待、排队、降级、拒绝服务等。
本文基于限流反射之一的计数器方式来实现限流
1.定义注解
- package com.cwf.framework.limit.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 Limit {
- /**
- * 资源的key,唯一
- * 作用:不同的接口,不同的流量控制
- */
- String key() default "";
-
- /**
- * 最多的访问限制次数
- */
- long count() default 7;
-
- /**
- * 过期时间也可以理解为单位时间,单位秒,默认60
- */
- long expire() default 60;
-
-
- /**
- * 提示语
- */
- String msg() default "系统繁忙,请稍后再试!";
- }

利用redis 的incr 高并发 原子性计数器来计数,当请求次数超过规定次数就抛出自定义异常,全局异常捕获异常信息返回给前台
- package com.cwf.framework.limit.aspectj;
-
- import com.cwf.common.core.controller.BaseController;
- import com.cwf.common.exception.base.MyException;
- import com.cwf.common.utils.ip.IpUtils;
- import com.cwf.framework.limit.annotation.Limit;
- import com.cwf.framework.redis.RedisService;
- import lombok.extern.slf4j.Slf4j;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestAttributes;
- import org.springframework.web.context.request.RequestContextHolder;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.concurrent.TimeUnit;
-
-
- /**
- * 限流服务
- */
- @SuppressWarnings("all")
- @Slf4j
- @Component
- @Aspect
- public class LimitAOP extends BaseController {
-
- @Autowired
- private RedisService redisService;
-
- @Pointcut("@annotation(com.cwf.framework.limit.annotation.Limit)")
- private void LimitPointcut() {
-
- }
-
- @Before("@annotation(limit)")
- public void before(JoinPoint point, Limit limit) throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException {
- // 获取RequestAttributes
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- // 从获取RequestAttributes中获取HttpServletRequest的信息
- assert requestAttributes != null;
- HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
-
- assert request != null;
- String path = request.getRequestURI();
- String ip = IpUtils.getIpAddress(request);
-
- //获取注解信息
- String key = limit.key();
- long count = limit.count();
- String msg = limit.msg();
- long expire = limit.expire();
-
- String redisKey = ip+path+key+getUserId();
- Long inc = redisService.inc(redisKey);
-
- if (inc==1){
- redisService.expire(redisKey, expire, TimeUnit.SECONDS);
- }
-
- if (inc > count){
- log.error("\n{}触发限制流量",key);
- throw new MyException(msg,400);
- }
-
-
-
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。