自定义注解+AOP+Guava实现限流

一.引入AOP和Guava依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>

    </dependencies>

二.自定义限流注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitFlow {
    String name() default "";
    double token() default 10;
}

三.定义Aop

@Component
@Aspect
public class LimitFlowAop {

    private ConcurrentHashMap<String, RateLimiter> concurrentHashMap = new ConcurrentHashMap<>();

    @Pointcut(value = "@annotation(com.jw.annotation.LimitFlow)")
    private void limitFlowControl(){

    }

    @Around(value = "limitFlowControl()")
    public Object around(ProceedingJoinPoint joinPoint){

        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        LimitFlow limitFlow = methodSignature.getMethod().getDeclaredAnnotation(LimitFlow.class);
        String name = limitFlow.name();
        double token = limitFlow.token();

        RateLimiter rateLimiter = concurrentHashMap.get(name);
        if (rateLimiter == null){
            rateLimiter = RateLimiter.create(token);
            concurrentHashMap.put(name,rateLimiter);
        }
        if (!rateLimiter.tryAcquire()) {
            return "服务器繁忙!!";
        }
        try {
            Object proceed = joinPoint.proceed();
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return "发送错误!!";
        }
    }
}

1.为什么使用环绕通知???

因为只有环绕通知可以决定是否执行目标方法!!

2.切点使用annotation的方式

对被自定义注解标注的目标方法进行增强

3.通过反射获取注解的属性值,name和token,并创建限流器RateLimiter

对目标方法进行限流

四.测试

超出注解中规定的QPS,则访问不到接口!!
从而达到限流的目的

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值