|
|
|
|
@ -2,14 +2,14 @@ package cn.iocoder.yudao.framework.idempotent.core.aop;
|
|
|
|
|
|
|
|
|
|
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
|
|
|
|
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
|
|
|
|
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
|
|
|
|
import cn.iocoder.yudao.framework.idempotent.core.annotation.Idempotent;
|
|
|
|
|
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
|
|
|
|
|
import cn.iocoder.yudao.framework.idempotent.core.redis.IdempotentRedisDAO;
|
|
|
|
|
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
import org.aspectj.lang.JoinPoint;
|
|
|
|
|
import org.aspectj.lang.ProceedingJoinPoint;
|
|
|
|
|
import org.aspectj.lang.annotation.Around;
|
|
|
|
|
import org.aspectj.lang.annotation.Aspect;
|
|
|
|
|
import org.aspectj.lang.annotation.Before;
|
|
|
|
|
import org.springframework.util.Assert;
|
|
|
|
|
|
|
|
|
|
import java.util.List;
|
|
|
|
|
@ -36,21 +36,33 @@ public class IdempotentAspect {
|
|
|
|
|
this.idempotentRedisDAO = idempotentRedisDAO;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Before("@annotation(idempotent)")
|
|
|
|
|
public void beforePointCut(JoinPoint joinPoint, Idempotent idempotent) {
|
|
|
|
|
@Around(value = "@annotation(idempotent)")
|
|
|
|
|
public Object beforePointCut(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
|
|
|
|
|
// 获得 IdempotentKeyResolver
|
|
|
|
|
IdempotentKeyResolver keyResolver = keyResolvers.get(idempotent.keyResolver());
|
|
|
|
|
Assert.notNull(keyResolver, "找不到对应的 IdempotentKeyResolver");
|
|
|
|
|
// 解析 Key
|
|
|
|
|
String key = keyResolver.resolver(joinPoint, idempotent);
|
|
|
|
|
|
|
|
|
|
// 锁定 Key。
|
|
|
|
|
// 1. 锁定 Key
|
|
|
|
|
boolean success = idempotentRedisDAO.setIfAbsent(key, idempotent.timeout(), idempotent.timeUnit());
|
|
|
|
|
// 锁定失败,抛出异常
|
|
|
|
|
if (!success) {
|
|
|
|
|
log.info("[beforePointCut][方法({}) 参数({}) 存在重复请求]", joinPoint.getSignature().toString(), joinPoint.getArgs());
|
|
|
|
|
throw new ServiceException(GlobalErrorCodeConstants.REPEATED_REQUESTS.getCode(), idempotent.message());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 2. 执行逻辑
|
|
|
|
|
try {
|
|
|
|
|
return joinPoint.proceed();
|
|
|
|
|
} catch (Throwable throwable) {
|
|
|
|
|
// 3. 异常时,删除 Key
|
|
|
|
|
// 参考美团 GTIS 思路:https://tech.meituan.com/2016/09/29/distributed-system-mutually-exclusive-idempotence-cerberus-gtis.html
|
|
|
|
|
if (idempotent.deleteKeyWhenException()) {
|
|
|
|
|
idempotentRedisDAO.delete(key);
|
|
|
|
|
}
|
|
|
|
|
throw throwable;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|