使用谷歌Guava的RateLimiter实现自定义限流注解


一、pom.xml

<dependencies>
        <!--  springboot 整合web组件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

二、限流注解

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CurrentLimitingAnnotation {
    /**
     * name 限流的名称
     *
     * @return
     */
    String name() default "";

    /**
     * 每秒 能够允许访问的次数 20 底层
     * 令牌桶
     *
     * @return
     */
    double maxPermits() default 20;
}

三、AOP

import com.google.common.util.concurrent.RateLimiter;
import com.qi.annotation.CurrentLimitingAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Aspect
public class CurrentLimitingAop {
    /**
     * google guava中提供了一个限流实现: RateLimiter,这个类设计的非常精巧,该类基于令牌桶算法(Token Bucket)来完成限流,
     * 可以适用于我们日常业务中大多数流控的场景,但鉴于使用场景的多样性,使用时也需要相当小心。
     */
    private ConcurrentHashMap<String,RateLimiter> rateLimiters = new ConcurrentHashMap<>();

    /**
     * 只要使用CurrentLimitingAnnotation注解就会被拦截。
     */
        @Around(value = "@annotation(com.qi.annotation.CurrentLimitingAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) {
        try {
            //获取拦截的方法名
            Signature sig = joinPoint.getSignature();
            //获取拦截的方法名
            MethodSignature methodSignature = (MethodSignature) sig;
            CurrentLimitingAnnotation currentLimitingAnnotation = methodSignature.getMethod().getDeclaredAnnotation(CurrentLimitingAnnotation.class);
            // 获取到该注解的name
            String name = currentLimitingAnnotation.name();
            // 获取该注解的token
            double maxPermits = currentLimitingAnnotation.maxPermits();
            // 判断该名称是否有创建RateLimiter
            RateLimiter rateLimiter = rateLimiters.get(name);
            if (rateLimiter == null) {
                rateLimiter = RateLimiter.create(maxPermits);
                rateLimiters.put(name, rateLimiter);
            }
            /**
             * 如果被限流的话
             */
            boolean result = rateLimiter.tryAcquire();
            if (!result) {
                return "当前访问人数过多,请稍后重试!";
            }
            Object proceedResult = joinPoint.proceed();// 目标方法   public String get() {}
            return proceedResult;
        } catch (Throwable throwable) {
            return "系统出现了错误!";
        }
    }
}

四、Controller

import com.qi.annotation.CurrentLimitingAnnotation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CurrentLimitingController {

    //private RateLimiter rateLimiter = RateLimiter.create(2.0);

    @GetMapping("/get")
    @CurrentLimitingAnnotation(name = "get", maxPermits = 1)
    public String get() {
        System.out.println("执行方法");
        return "my is get";
    }

    @GetMapping("/query")
    @CurrentLimitingAnnotation(name = "qbh-query", maxPermits = 5)
    public String query() {
        System.out.println("执行方法");
        return "my is query";
    }
}

五、在浏览器中测试效果

当连续多次点击时:
当连续多次点击时


  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值