update 优化 限流注解 key 支持简单 spel 表达式

This commit is contained in:
疯狂的狮子Li 2023-04-03 13:23:32 +08:00
parent 0662756e8c
commit 5b43d0e29f
2 changed files with 21 additions and 1 deletions

View File

@ -49,4 +49,16 @@ public class RedisRateLimiterController {
return R.ok("操作成功", value);
}
/**
* 测试请求IP限流(key基于参数获取)
* 同一IP请求受影响
*
* 简单变量获取 #变量 复杂表达式 #{#变量 != 1 ? 1 : 0}
*/
@RateLimiter(count = 2, time = 10, limitType = LimitType.IP, key = "#value")
@GetMapping("/testObj")
public R<String> testObj(String value) {
return R.ok("操作成功", value);
}
}

View File

@ -18,6 +18,7 @@ import org.redisson.api.RateType;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
@ -102,7 +103,14 @@ public class RateLimiterAspect {
}
// 解析返回给key
try {
key = parser.parseExpression(key, parserContext).getValue(context, String.class) + ":";
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解析异常!请联系管理员!");
}