package com.qianwen.core.redis.ratelimiter;
|
|
import java.lang.reflect.Method;
|
import java.util.concurrent.TimeUnit;
|
import org.aspectj.lang.ProceedingJoinPoint;
|
import org.aspectj.lang.annotation.Around;
|
import org.aspectj.lang.annotation.Aspect;
|
import org.aspectj.lang.reflect.MethodSignature;
|
import com.qianwen.core.tool.spel.BladeExpressionEvaluator;
|
import com.qianwen.core.tool.utils.StringUtil;
|
import org.springframework.beans.BeansException;
|
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContextAware;
|
import org.springframework.context.expression.AnnotatedElementKey;
|
import org.springframework.expression.EvaluationContext;
|
import org.springframework.lang.NonNull;
|
import org.springframework.util.Assert;
|
|
@Aspect
|
/* loaded from: blade-starter-redis-9.3.0.0-SNAPSHOT.jar:org/springblade/core/redis/ratelimiter/RedisRateLimiterAspect.class */
|
public class RedisRateLimiterAspect implements ApplicationContextAware {
|
private final BladeExpressionEvaluator evaluator = new BladeExpressionEvaluator();
|
private final RedisRateLimiterClient rateLimiterClient;
|
private ApplicationContext applicationContext;
|
|
public RedisRateLimiterAspect(final RedisRateLimiterClient rateLimiterClient) {
|
this.rateLimiterClient = rateLimiterClient;
|
}
|
|
@Around("@annotation(limiter)")
|
public Object aroundRateLimiter(ProceedingJoinPoint point, RateLimiter limiter) throws Throwable {
|
String rateKey;
|
String limitKey = limiter.value();
|
Assert.hasText(limitKey, "@RateLimiter value must have length; it must not be null or empty");
|
String limitParam = limiter.param();
|
if (StringUtil.isNotBlank(limitParam)) {
|
String evalAsText = evalLimitParam(point, limitParam);
|
rateKey = limitKey + ':' + evalAsText;
|
} else {
|
rateKey = limitKey;
|
}
|
long max = limiter.max();
|
long ttl = limiter.ttl();
|
TimeUnit timeUnit = limiter.timeUnit();
|
|
return this.rateLimiterClient.allow(rateKey, max, ttl, timeUnit, point::proceed);
|
|
}
|
|
private String evalLimitParam(ProceedingJoinPoint point, String limitParam) {
|
MethodSignature ms = (MethodSignature)point.getSignature();
|
Method method = ms.getMethod();
|
Object[] args = point.getArgs();
|
Object target = point.getTarget();
|
Class<?> targetClass = target.getClass();
|
EvaluationContext context = this.evaluator.createContext(method, args, target, targetClass, this.applicationContext);
|
AnnotatedElementKey elementKey = new AnnotatedElementKey(method, targetClass);
|
return this.evaluator.evalAsText(limitParam, elementKey, context);
|
}
|
|
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
|
this.applicationContext = applicationContext;
|
}
|
}
|