SpringBoot利用限速器RateLimiter实现单机限流的示例代码
作者:任未然 发布时间:2023-04-05 19:57:50
标签:SpringBoot,单机,限流
一. 概述
参考开源项目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;
/**
* qps (每秒并发量)
*/
@AliasFor("qps") double value() default NOT_LIMITED;
/**
* qps (每秒并发量)
*/
@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 {
/**
* 接口每秒只能请求一次,不等待
* @return
*/
@RateLimiter(value = 1.0)
@GetMapping("/test1")
public Dict test1() {
log.info("【test1】被执行了。。。。。");
return Dict.create().set("msg", "hello,world!").set("description", "别想一直看到我,不信你快速刷新看看~");
}
/**
* 接口每秒只能请求一次,等待一秒
* @return
*/
@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", "别想一直看到我,不信你快速刷新看看~");
}
}
来源:https://www.jianshu.com/p/6e812f307f06


猜你喜欢
- 一. 方法重写在面向对象中,实现多态的必备条件是继承、重写和向上转型,现在我们已经学习了什么是继承。接下来我们再来学习什么是方法重写,这是我
- 一、 添加 maven 依赖<dependency> <groupId>com.google.guava
- C++中一个重要的特性就是指针,指针不仅具有获得地址的能力,还具有操作地址的能力。指针可以用于数组、或作为函数的参数,用来访问内存和对内存的
- 本文实例讲述了C#实现自定义Dictionary类。分享给大家供大家参考。具体如下:1.关于MyDictionary类本文中实现的MyDic
- 有的人的电脑在使用 IntelliJ IDEA 的svn 时候,无法保存密码,输入密码时,勾选保存密码还是无效。每次都的输入密码,一次浪费2
- 概述背景函数式编程的理论基础是阿隆佐·丘奇(Alonzo Church)于 1930 年代提出的 &lambd
- 栈和队列:都是线性表,都是基于List基础上的实现线性表:数组,链表,字符串,栈,队列元素按照一条“直线&rdq
- 环境与版本hibernate 版本:Hibernate 4.2.2 (下载后的文件名为hibernate-release-4.2.2.Fin
- 只使用try和finally不使用catch的原因和场景JDK并发工具包中,很多异常处理都使用了如下的结构,如AbstractExecuto
- 1、Java主要特点简单性、跨平台性、分布性、安全性、健壮性、平 * 立与可移植性、多线程、动态性、面向对象的编程语言、支持垃圾自动收集处理等
- 一、线程的状态NEW: 安排了工作, 还未开始行动RUNNABLE: 可工作的. 又可以分成正在工作中和即将开始工作.BLOCKED: 这几
- mybatis if test判断入参的值1.第一种判断方式<if test=' requisition != null an
- Java未被捕获的异常在你学习在程序中处理异常之前,看一看如果你不处理它们会有什么情况发生是很有好处的。下面的小程序包括一个故意导致被零除错
- Android开发之Android.mk模板的实例详解关于Android NDK开发的文章已经比较多了,我的博客中也分享了很多NDK开发相关
- 字符流是针对字符数据的特点进行过优化的,因而提供一些面向字符的有用特性,字符流的源或目标通常是文本文件。 Reader和Writer是jav
- 这种结果的原因在于,Random()函数的默认种子是时间,但在循环中产生随机数时,由于运算速度太快,用做种子的时间是相同的(毫秒级),因此产
- 以下图中TV VOD两个按键为例,文章中所涉及到的文件只写文件名,因每个方案的路径各不相同,请自行全局搜索文件。 1.获取按键的扫
- 【前言】面向资源的 Restful 风格的 api 接口本着简洁,资源,便于扩展,便于理解等等各项优势,在如今的系统服务中越来越受欢迎。.n
- package cn.hackcoder.beautyreader.broadcast;import android.content.Bro
- Unix时间戳最小单位是秒,开始时间为格林威治标准时间1970-01-01 00:00:00ConvertIntDateTime方法的基本思