update 优化 限流功能 redis key 生成规则 以功能头+url+ip+key格式
fix 修复 !pr290 的问题
This commit is contained in:
parent
995578c561
commit
2a46cdbd88
@ -1,6 +1,8 @@
|
||||
package com.ruoyi.framework.aspectj;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import com.ruoyi.common.annotation.RateLimiter;
|
||||
import com.ruoyi.common.constant.CacheConstants;
|
||||
import com.ruoyi.common.enums.LimitType;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.utils.MessageUtils;
|
||||
@ -35,16 +37,23 @@ import java.lang.reflect.Method;
|
||||
@Component
|
||||
public class RateLimiterAspect {
|
||||
|
||||
//定义spel表达式解析器
|
||||
/**
|
||||
* 定义spel表达式解析器
|
||||
*/
|
||||
private final ExpressionParser parser = new SpelExpressionParser();
|
||||
//定义spel解析模版
|
||||
/**
|
||||
* 定义spel解析模版
|
||||
*/
|
||||
private final ParserContext parserContext = new TemplateParserContext();
|
||||
//定义spel上下文对象进行解析
|
||||
/**
|
||||
* 定义spel上下文对象进行解析
|
||||
*/
|
||||
private final EvaluationContext context = new StandardEvaluationContext();
|
||||
//方法参数解析器
|
||||
/**
|
||||
* 方法参数解析器
|
||||
*/
|
||||
private final ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
|
||||
|
||||
|
||||
@Before("@annotation(rateLimiter)")
|
||||
public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable {
|
||||
int time = rateLimiter.time();
|
||||
@ -85,6 +94,9 @@ public class RateLimiterAspect {
|
||||
Object[] args = point.getArgs();
|
||||
// 获取方法上参数的名称
|
||||
String[] parameterNames = pnd.getParameterNames(method);
|
||||
if (ArrayUtil.isEmpty(parameterNames)) {
|
||||
throw new ServiceException("限流key解析异常!请联系管理员!");
|
||||
}
|
||||
for (int i = 0; i < parameterNames.length; i++) {
|
||||
context.setVariable(parameterNames[i], args[i]);
|
||||
}
|
||||
@ -95,15 +107,15 @@ public class RateLimiterAspect {
|
||||
throw new ServiceException("限流key解析异常!请联系管理员!");
|
||||
}
|
||||
}
|
||||
StringBuilder stringBuffer = new StringBuilder(key);
|
||||
StringBuilder stringBuffer = new StringBuilder(CacheConstants.RATE_LIMIT_KEY);
|
||||
stringBuffer.append(ServletUtils.getRequest().getRequestURI()).append(":");
|
||||
if (rateLimiter.limitType() == LimitType.IP) {
|
||||
// 获取请求ip
|
||||
stringBuffer.append(ServletUtils.getClientIP()).append("-");
|
||||
stringBuffer.append(ServletUtils.getClientIP()).append(":");
|
||||
} else if (rateLimiter.limitType() == LimitType.CLUSTER) {
|
||||
// 获取客户端实例id
|
||||
stringBuffer.append(RedisUtils.getClient().getId()).append("-");
|
||||
stringBuffer.append(RedisUtils.getClient().getId()).append(":");
|
||||
}
|
||||
stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
|
||||
return stringBuffer.toString();
|
||||
return stringBuffer.append(key).toString();
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user