pull/109/head
YunaiV 2024-04-10 20:49:59 +08:00
commit 7766c82f6c
9 changed files with 95 additions and 23 deletions

View File

@ -4,6 +4,7 @@ import cn.iocoder.yudao.framework.idempotent.core.aop.IdempotentAspect;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.DefaultIdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.DefaultIdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.ExpressionIdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.ExpressionIdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.UserIdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.redis.IdempotentRedisDAO; import cn.iocoder.yudao.framework.idempotent.core.redis.IdempotentRedisDAO;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration; import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
@ -32,6 +33,11 @@ public class YudaoIdempotentConfiguration {
return new DefaultIdempotentKeyResolver(); return new DefaultIdempotentKeyResolver();
} }
@Bean
public UserIdempotentKeyResolver userIdempotentKeyResolver() {
return new UserIdempotentKeyResolver();
}
@Bean @Bean
public ExpressionIdempotentKeyResolver expressionIdempotentKeyResolver() { public ExpressionIdempotentKeyResolver expressionIdempotentKeyResolver() {
return new ExpressionIdempotentKeyResolver(); return new ExpressionIdempotentKeyResolver();

View File

@ -2,6 +2,8 @@ package cn.iocoder.yudao.framework.idempotent.core.annotation;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.DefaultIdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.DefaultIdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.ExpressionIdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.UserIdempotentKeyResolver;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
@ -36,6 +38,10 @@ public @interface Idempotent {
/** /**
* 使 Key * 使 Key
*
* @see DefaultIdempotentKeyResolver
* @see UserIdempotentKeyResolver
* @see ExpressionIdempotentKeyResolver {@link #keyArg()}
*/ */
Class<? extends IdempotentKeyResolver> keyResolver() default DefaultIdempotentKeyResolver.class; Class<? extends IdempotentKeyResolver> keyResolver() default DefaultIdempotentKeyResolver.class;
/** /**
@ -43,4 +49,15 @@ public @interface Idempotent {
*/ */
String keyArg() default ""; String keyArg() default "";
/**
* Key
*
* Key
* Key
*
* deleteWhenSuccess Key
* 使 @Lock4j
*/
boolean deleteKeyWhenException() default true;
} }

View File

@ -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.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; 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.annotation.Idempotent;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver; import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
import cn.iocoder.yudao.framework.idempotent.core.redis.IdempotentRedisDAO; import cn.iocoder.yudao.framework.idempotent.core.redis.IdempotentRedisDAO;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import lombok.extern.slf4j.Slf4j; 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.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.List; import java.util.List;
@ -36,21 +36,33 @@ public class IdempotentAspect {
this.idempotentRedisDAO = idempotentRedisDAO; this.idempotentRedisDAO = idempotentRedisDAO;
} }
@Before("@annotation(idempotent)") @Around(value = "@annotation(idempotent)")
public void beforePointCut(JoinPoint joinPoint, Idempotent idempotent) { public Object beforePointCut(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
// 获得 IdempotentKeyResolver // 获得 IdempotentKeyResolver
IdempotentKeyResolver keyResolver = keyResolvers.get(idempotent.keyResolver()); IdempotentKeyResolver keyResolver = keyResolvers.get(idempotent.keyResolver());
Assert.notNull(keyResolver, "找不到对应的 IdempotentKeyResolver"); Assert.notNull(keyResolver, "找不到对应的 IdempotentKeyResolver");
// 解析 Key // 解析 Key
String key = keyResolver.resolver(joinPoint, idempotent); String key = keyResolver.resolver(joinPoint, idempotent);
// 锁定 Key // 1. 锁定 Key
boolean success = idempotentRedisDAO.setIfAbsent(key, idempotent.timeout(), idempotent.timeUnit()); boolean success = idempotentRedisDAO.setIfAbsent(key, idempotent.timeout(), idempotent.timeUnit());
// 锁定失败,抛出异常 // 锁定失败,抛出异常
if (!success) { if (!success) {
log.info("[beforePointCut][方法({}) 参数({}) 存在重复请求]", joinPoint.getSignature().toString(), joinPoint.getArgs()); log.info("[beforePointCut][方法({}) 参数({}) 存在重复请求]", joinPoint.getSignature().toString(), joinPoint.getArgs());
throw new ServiceException(GlobalErrorCodeConstants.REPEATED_REQUESTS.getCode(), idempotent.message()); 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;
}
} }
} }

View File

@ -7,7 +7,7 @@ import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResol
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
/** /**
* Key 使 + Key * Key 使 + Key
* *
* Key 使 MD5 * Key 使 MD5
* *

View File

@ -0,0 +1,28 @@
package cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.iocoder.yudao.framework.idempotent.core.annotation.Idempotent;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.IdempotentKeyResolver;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import org.aspectj.lang.JoinPoint;
/**
* Key 使 + + userId + userType Key
*
* Key 使 MD5
*
* @author
*/
public class UserIdempotentKeyResolver implements IdempotentKeyResolver {
@Override
public String resolver(JoinPoint joinPoint, Idempotent idempotent) {
String methodName = joinPoint.getSignature().toString();
String argsStr = StrUtil.join(",", joinPoint.getArgs());
Long userId = WebFrameworkUtils.getLoginUserId();
Integer userType = WebFrameworkUtils.getLoginUserType();
return SecureUtil.md5(methodName + argsStr + userId + userType);
}
}

View File

@ -29,6 +29,11 @@ public class IdempotentRedisDAO {
return redisTemplate.opsForValue().setIfAbsent(redisKey, "", timeout, timeUnit); return redisTemplate.opsForValue().setIfAbsent(redisKey, "", timeout, timeUnit);
} }
public void delete(String key) {
String redisKey = formatKey(key);
redisTemplate.delete(redisKey);
}
private static String formatKey(String key) { private static String formatKey(String key) {
return String.format(IDEMPOTENT, key); return String.format(IDEMPOTENT, key);
} }

View File

@ -2,9 +2,9 @@ package cn.iocoder.yudao.framework.jackson.config;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.jackson.core.databind.LocalDateTimeDeserializer;
import cn.iocoder.yudao.framework.jackson.core.databind.LocalDateTimeSerializer;
import cn.iocoder.yudao.framework.jackson.core.databind.NumberSerializer; import cn.iocoder.yudao.framework.jackson.core.databind.NumberSerializer;
import cn.iocoder.yudao.framework.jackson.core.databind.TimestampLocalDateTimeDeserializer;
import cn.iocoder.yudao.framework.jackson.core.databind.TimestampLocalDateTimeSerializer;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
@ -37,13 +37,13 @@ public class YudaoJacksonAutoConfiguration {
.addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE) .addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE)
.addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE) .addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE)
.addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE) .addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE)
// 新增 LocalDateTime 序列化、反序列化规则 // 新增 LocalDateTime 序列化、反序列化规则,使用 Long 时间戳
.addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE) .addSerializer(LocalDateTime.class, TimestampLocalDateTimeSerializer.INSTANCE)
.addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE); .addDeserializer(LocalDateTime.class, TimestampLocalDateTimeDeserializer.INSTANCE);
// 1.2 注册到 objectMapper // 1.2 注册到 objectMapper
objectMappers.forEach(objectMapper -> objectMapper.registerModule(simpleModule)); objectMappers.forEach(objectMapper -> objectMapper.registerModule(simpleModule));
// 2. 设置 objectMapper 到 JsonUtils { // 2. 设置 objectMapper 到 JsonUtils
JsonUtils.init(CollUtil.getFirst(objectMappers)); JsonUtils.init(CollUtil.getFirst(objectMappers));
log.info("[init][初始化 JsonUtils 成功]"); log.info("[init][初始化 JsonUtils 成功]");
return new JsonUtils(); return new JsonUtils();

View File

@ -10,16 +10,18 @@ import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
/** /**
* LocalDateTime * LocalDateTime
* <p> *
* LocalDateTime * @author
*/ */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { public class TimestampLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
public static final LocalDateTimeDeserializer INSTANCE = new LocalDateTimeDeserializer(); public static final TimestampLocalDateTimeDeserializer INSTANCE = new TimestampLocalDateTimeDeserializer();
@Override @Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
// 将 Long 时间戳,转换为 LocalDateTime 对象
return LocalDateTime.ofInstant(Instant.ofEpochMilli(p.getValueAsLong()), ZoneId.systemDefault()); return LocalDateTime.ofInstant(Instant.ofEpochMilli(p.getValueAsLong()), ZoneId.systemDefault());
} }
} }

View File

@ -9,16 +9,18 @@ import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
/** /**
* LocalDateTime * LocalDateTime
* <p> *
* LocalDateTime * @author
*/ */
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { public class TimestampLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
public static final LocalDateTimeSerializer INSTANCE = new LocalDateTimeSerializer(); public static final TimestampLocalDateTimeSerializer INSTANCE = new TimestampLocalDateTimeSerializer();
@Override @Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 将 LocalDateTime 对象,转换为 Long 时间戳
gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); gen.writeNumber(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
} }
} }