Java服务接口层面限流
参考:https://www.cnblogs.com/myseries/p/12634557.html
https://my.oschina.net/u/3768341/blog/3054276
方案
核心思路是使用Guava 包的 RateLimiter 做限流
结合aop使用注解打到接口上 改参数即可实现每个接口独立控制限流次数
per.times.xxx 即 QPS,设置多少就是每秒最大不超过次数
@RequestMapping("/testAnnotation")
@AopRateLimit(configKey = "${per.times.testAnnotation}")
public String testAnnotation() {
return "success";
}
@AopRateLimit(configKey = “${per.times.testAnnotation}”)
per.times.testAnnotation 这里是外部化配置(从nacos读取参数),做到不需要重启的热部署,各接口独立
当接口QPS大于1的时候就会返回 “服务器繁忙,请稍后再试!”
自测多次,10个请求 1个会成功,其余被拦截,返回自定义提示。
以下为使用 Jmeter压测进行 10个并发测试请求
自定义注解:
package com.yww.common.annotation;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @author Akizora
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AopRateLimit {
/**
* 读取 nacos 配置的外部化参数
*
* @return
*/
String configKey() default "";
/**
* 默认空字符串
*
* @return
*/
String value() default "";
/**
* 每秒向桶中放入令牌的数量 默认最大即不做限流
*
* @return
*/
double perSecond() default Double.MAX_VALUE;
/**
* 获取令牌的等待时间 默认500
*
* @return
*/
int timeOut() default 500;
/**
* 超时时间单位
*
* @return
*/
TimeUnit timeOutUnit() default TimeUnit.MILLISECONDS;
}
aop切面:
package com.yww.action.web.aop;
import com.google.common.util.concurrent.RateLimiter;
import com.yww.common.annotation.AopRateLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.Method;
/**
* 使用guava包的 rateLimiter 实现的令牌桶限流,支持各接口独立配置限流参数
*
* @author dzc
*/
@SuppressWarnings("all")
@Aspect
@Component
public class AopRateLimitAspect {
@Autowired
private ConfigurableEnvironment environment;
private final static Logger logger = LoggerFactory.getLogger(AopRateLimitAspect.class);
private final RateLimiter rateLimiter = RateLimiter.create(Double.MAX_VALUE);
/**
* 定义切点
* 1、通过扫包切入
* 2、带有指定注解切入
*/
@Pointcut("@annotation(com.yww.common.annotation.AopRateLimit)")
public void checkPointcut() {
}
@ResponseBody
@Around(value = "checkPointcut()")
public Object aroundNotice(ProceedingJoinPoint pjp) throws Throwable {
logger.info("拦截到了{}方法...", pjp.getSignature().getName());
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//获取目标方法
Method targetMethod = methodSignature.getMethod();
if (targetMethod.isAnnotationPresent(AopRateLimit.class)) {
//获取目标方法的@AopRateLimit注解
AopRateLimit AopRateLimit = targetMethod.getAnnotation(AopRateLimit.class);
//从环境变量中获取
String perSecond = environment.resolvePlaceholders(String.valueOf(AopRateLimit.configKey()));
logger.info("AopRateLimit configKey,{}", perSecond);
rateLimiter.setRate(Double.valueOf(perSecond));
if (!rateLimiter.tryAcquire(AopRateLimit.timeOut(), AopRateLimit.timeOutUnit())) {
return "服务器繁忙,请稍后再试!";
}
}
return pjp.proceed();
}
}
Aop 核心代码
- 从容器上下文中获取外部化配置参数
- 使用RateLimiter的tryAcquire令牌桶算法实现限流
同时nacos配置中心已集成好,
在 framework 项目引入 config 依赖,
spring-cloud-starter-alibaba-nacos-config
并在bootstrap.properties里加入配置
#nacos做配置中心
spring.cloud.nacos.config.server-addr=192.168.161.251:8848
#配置使得nacos支持properties读取值
spring.cloud.nacos.config.file-extension=properties
spring.cloud.nacos.config.group=DEFAULT_GROUP
最后在 nacos 界面新增不同环境(dev,test,prod独立配置,可以通过Group设置)的配置文件,将原来项目中的 application-test.properties 文件复制迁移。