栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot 接口限流 API限流 基于注解实现限流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot 接口限流 API限流 基于注解实现限流

基于注解实现接口限流
  • 一、代码实现
    • 1.引入依赖
    • 2.自定义注解 CurrentLimitingAnnotation
    • 3.接口测试
    • 4.AOP 拦截注解实现限流
    • 5.启动类
    • 6.测试

一、代码实现 1.引入依赖
 
        
            org.springframework.boot
            spring-boot-starter-web
        
 
        
            com.google.guava
            guava
            18.0
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
2.自定义注解 CurrentLimitingAnnotation
 

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentLimitingAnnotation {

    
    String name() default "";

    
    double token() default 5;
}
3.接口测试
@RestController
public class AopController {
    
     
    @GetMapping("/add")
    @CurrentLimitingAnnotation(name = "add", token = 1)
    public String add() {
        System.out.println("add.............");
        return "success";
    }
}

4.AOP 拦截注解实现限流
@Aspect
@Component
public class CurrentLimitingAop {

    private ConcurrentHashMap rateLimiterConcurrentHashMap = new ConcurrentHashMap<>();

    @Around(value = "@annotation(com.sean.satoken.annotations.CurrentLimitingAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) {

        try {
            // 获取拦截的方法名
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

            // 获取该方法的注解 CurrentLimitingAnnotation
            CurrentLimitingAnnotation currentLimitingAnnotation =
                    methodSignature.getMethod().getDeclaredAnnotation(CurrentLimitingAnnotation.class);

            //获取到注解的name,token
            String name = currentLimitingAnnotation.name();
            double token = currentLimitingAnnotation.token();

            //判断改名称是否有创建rateLimiter 没有则创建,有则拿来用
            RateLimiter rateLimiter = rateLimiterConcurrentHashMap.get(name);

            if (rateLimiter == null) {
                rateLimiterConcurrentHashMap.put(name, RateLimiter.create(token));
            }

            if (!rateLimiter.tryAcquire()) {
                return "请求过于频繁,请稍后再试";
            }

            return joinPoint.proceed();

        } catch (Throwable throwable) {
            return "系统错误!";
        }
    }
}

5.启动类
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
6.测试

访问接口 ip:port/add,当前接口token设置了1秒,如果一秒内多次访问 return ”请求过于频繁,请稍后再试“

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/271338.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号