优化RateLimiter注解使用体验

This commit is contained in:
数据小王子 2024-03-06 10:14:00 +08:00
parent 7c649bb5b2
commit b8ab413eab
2 changed files with 37 additions and 46 deletions

View File

@ -1,29 +1,29 @@
package com.ruoyi.common.ratelimiter.aspectj; package com.ruoyi.common.ratelimiter.aspectj;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.ratelimiter.annotation.RateLimiter;
import com.ruoyi.common.ratelimiter.enums.LimitType;
import com.ruoyi.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import com.ruoyi.common.core.constant.GlobalConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.MessageUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.ratelimiter.annotation.RateLimiter;
import com.ruoyi.common.ratelimiter.enums.LimitType;
import com.ruoyi.common.redis.utils.RedisUtils;
import org.redisson.api.RateType; import org.redisson.api.RateType;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression; import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser; import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext; import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext; import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -44,21 +44,18 @@ public class RateLimiterAspect {
* 定义spel解析模版 * 定义spel解析模版
*/ */
private final ParserContext parserContext = new TemplateParserContext(); private final ParserContext parserContext = new TemplateParserContext();
/**
* 定义spel上下文对象进行解析
*/
private final EvaluationContext context = new StandardEvaluationContext();
/** /**
* 方法参数解析器 * 方法参数解析器
*/ */
private final ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer(); private final ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
@Before("@annotation(rateLimiter)") @Before("@annotation(rateLimiter)")
public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable { public void doBefore(JoinPoint point, RateLimiter rateLimiter) {
int time = rateLimiter.time(); int time = rateLimiter.time();
int count = rateLimiter.count(); int count = rateLimiter.count();
String combineKey = getCombineKey(rateLimiter, point);
try { try {
String combineKey = getCombineKey(rateLimiter, point);
RateType rateType = RateType.OVERALL; RateType rateType = RateType.OVERALL;
if (rateLimiter.limitType() == LimitType.CLUSTER) { if (rateLimiter.limitType() == LimitType.CLUSTER) {
rateType = RateType.PER_CLIENT; rateType = RateType.PER_CLIENT;
@ -76,42 +73,29 @@ public class RateLimiterAspect {
if (e instanceof ServiceException) { if (e instanceof ServiceException) {
throw e; throw e;
} else { } else {
throw new RuntimeException("服务器限流异常,请稍候再试"); throw new RuntimeException("服务器限流异常,请稍候再试", e);
} }
} }
} }
public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) { private String getCombineKey(RateLimiter rateLimiter, JoinPoint point) {
String key = rateLimiter.key(); String key = rateLimiter.key();
// 获取方法(通过方法签名来获取) if (StringUtils.isNotBlank(key)) {
MethodSignature signature = (MethodSignature) point.getSignature(); MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod(); Method targetMethod = signature.getMethod();
Class<?> targetClass = method.getDeclaringClass();
// 判断是否是spel格式
if (StringUtils.containsAny(key, "#")) {
// 获取参数值
Object[] args = point.getArgs(); Object[] args = point.getArgs();
// 获取方法上参数的名称 //noinspection DataFlowIssue
String[] parameterNames = pnd.getParameterNames(method); MethodBasedEvaluationContext context =
if (ArrayUtil.isEmpty(parameterNames)) { new MethodBasedEvaluationContext(null, targetMethod, args, pnd);
throw new ServiceException("限流key解析异常!请联系管理员!"); context.setBeanResolver(new BeanFactoryResolver(SpringUtils.getBeanFactory()));
} Expression expression;
for (int i = 0; i < parameterNames.length; i++) { if (StringUtils.startsWith(key, parserContext.getExpressionPrefix())
context.setVariable(parameterNames[i], args[i]); && StringUtils.endsWith(key, parserContext.getExpressionSuffix())) {
} expression = parser.parseExpression(key, parserContext);
// 解析返回给key } else {
try { expression = parser.parseExpression(key);
Expression expression;
if (StringUtils.startsWith(key, parserContext.getExpressionPrefix())
&& StringUtils.endsWith(key, parserContext.getExpressionSuffix())) {
expression = parser.parseExpression(key, parserContext);
} else {
expression = parser.parseExpression(key);
}
key = expression.getValue(context, String.class) + ":";
} catch (Exception e) {
throw new ServiceException("限流key解析异常!请联系管理员!");
} }
key = expression.getValue(context, String.class);
} }
StringBuilder stringBuffer = new StringBuilder(GlobalConstants.RATE_LIMIT_KEY); StringBuilder stringBuffer = new StringBuilder(GlobalConstants.RATE_LIMIT_KEY);
stringBuffer.append(ServletUtils.getRequest().getRequestURI()).append(":"); stringBuffer.append(ServletUtils.getRequest().getRequestURI()).append(":");

View File

@ -0,0 +1,7 @@
{
"com.ruoyi.common.ratelimiter.annotation.RateLimiter@key": {
"method": {
"parameters": true
}
}
}