iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot利用限速器RateLimiter实现单机限流的示例代码
  • 663
分享到

SpringBoot利用限速器RateLimiter实现单机限流的示例代码

2024-04-02 19:04:59 663人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录一. 概述二. SpringBootDemo2.1 依赖2.2 application.yml2.3 启动类2.4 定义一个限流注解 RateLimiter.java2.5 代理

一. 概述

参考开源项目https://GitHub.com/xkcoding/spring-boot-demo

在系统运维中, 有时候为了避免用户的恶意刷接口, 会加入一定规则的限流, 本Demo使用速率限制器com.xkcoding.ratelimit.guava.annotation.RateLimiter实现单机版的限流

二. SpringBootDemo

2.1 依赖

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

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

    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
    </dependency>

    <dependency>
      <groupId>com.Google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

2.2 application.yml

server:
  port: 8080
  servlet:
    context-path: /demo

2.3 启动类

@SpringBootApplication
public class SpringBootDemoRatelimitGuavaApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoRatelimitGuavaApplication.class, args);
    }
}

2.4 定义一个限流注解 RateLimiter.java

注意代码里使用了 AliasFor 设置一组属性的别名,所以获取注解的时候,需要通过 Spring 提供的注解工具类 AnnotationUtils 获取,不可以通过 AOP 参数注入的方式获取,否则有些属性的值将会设置不进去。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter {
    int NOT_LIMITED = 0;

    
    @AliasFor("qps") double value() default NOT_LIMITED;

    
    @AliasFor("value") double qps() default NOT_LIMITED;

    
    int timeout() default 0;

    
    TimeUnit timeUnit() default TimeUnit.MICROSECONDS;
}

2.5 代理: RateLimiterAspect.java

@Slf4j
@Aspect
@Component
public class RateLimiterAspect {
    
    private static final ConcurrentMap<String, com.google.common.util.concurrent.RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.xkcoding.ratelimit.guava.annotation.RateLimiter)")
    public void rateLimit() {

    }

    @Around("rateLimit()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        // 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
        RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.class);
        if (rateLimiter != null && rateLimiter.qps() > RateLimiter.NOT_LIMITED) {
            double qps = rateLimiter.qps();
            // TODO 这个key可以根据具体需求配置,例如根据ip限制,或用户
            String key = method.getDeclarinGClass().getName() + StrUtil.DOT + method.getName();
            if (RATE_LIMITER_CACHE.get(key) == null) {
                // 初始化 QPS
                RATE_LIMITER_CACHE.put(key, com.google.common.util.concurrent.RateLimiter.create(qps));
            }

            // 尝试获取令牌
            if (RATE_LIMITER_CACHE.get(key) != null && !RATE_LIMITER_CACHE.get(key).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
                throw new RuntimeException("手速太快了,慢点儿吧~");
            }
        }
        return point.proceed();
    }
}

2.6 使用

@Slf4j
@RestController
public class TestController {

    
    @RateLimiter(value = 1.0)
    @GetMapping("/test1")
    public Dict test1() {
        log.info("【test1】被执行了。。。。。");
        return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~");
    }

    
    @RateLimiter(value = 1.0, timeout = 1,timeUnit = TimeUnit.SECONDS)
    @GetMapping("/test3")
    public Dict test3() {
        log.info("【test3】被执行了。。。。。");
        return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~");
    }
}

到此这篇关于SpringBoot利用限速器RateLimiter实现单机限流的示例代码的文章就介绍到这了,更多相关SpringBoot 单机限流 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot利用限速器RateLimiter实现单机限流的示例代码

本文链接: https://www.lsjlt.com/news/163117.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作