您好,登录后才能下订单哦!
SpringBoot利用限速器RateLimiter怎么实现单机限流,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
参考开源项目https://github.com/xkcoding/spring-boot-demo
在系统运维中, 有时候为了避免用户的恶意刷接口, 会加入一定规则的限流, 本Demo使用速率限制器com.xkcoding.ratelimit.guava.annotation.RateLimiter实现单机版的限流
<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>
server: port: 8080 servlet: context-path: /demo
@SpringBootApplication
public class SpringBootDemoRatelimitGuavaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoRatelimitGuavaApplication.class, args);
}
}注意代码里使用了 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;
}@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();
}
}@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", "别想一直看到我,不信你快速刷新看看~");
}
}springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。
看完上述内容,你们掌握SpringBoot利用限速器RateLimiter怎么实现单机限流的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。