fix(uboot-common): 幂等性修改redis key通过线程存储

This commit is contained in:
chuhang
2021-09-30 09:44:47 +08:00
parent 9724d7ae1d
commit a256bc0ff4

View File

@ -5,6 +5,7 @@ import com.chinaunicom.mall.ebtp.common.exception.common.CommonExceptionEnum;
import com.chinaunicom.mall.ebtp.common.idempotent.annotation.Idempotent;
import com.chinaunicom.mall.ebtp.common.util.HttpContextUtils;
import com.chinaunicom.mall.ebtp.common.util.JsonUtils;
import io.netty.util.concurrent.FastThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
@ -20,6 +21,7 @@ import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
@ -35,6 +37,9 @@ public class IdempotentAspect {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**redis键值*/
public static final FastThreadLocal<String> REDIS_KEY = new FastThreadLocal<>();
@Pointcut("@annotation(com.chinaunicom.mall.ebtp.common.idempotent.annotation.Idempotent)")
public void pointCut() {
}
@ -52,6 +57,10 @@ public class IdempotentAspect {
Idempotent idempotent = method.getAnnotation(Idempotent.class);
String key = getKey(joinPoint, request);
/*清理线程*/
this.removeThreadLocal();
/*启用线程*/
REDIS_KEY.set(key);
long expireTime = idempotent.expireTime();
String info = idempotent.info();
@ -87,21 +96,23 @@ public class IdempotentAspect {
}
@After("pointCut()")
public void afterPointCut(JoinPoint joinPoint) {
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
String key = getKey(joinPoint, request);
public void afterPointCut() {
String key = REDIS_KEY.get();
Object object = redisTemplate.opsForValue().get(key);
Optional.ofNullable(object).ifPresent(o-> {
boolean delKey = (boolean) o;
if (delKey) {
redisTemplate.delete(key);
log.info("[idempotent]:has removed key={}", key);
}
});
/*清理线程*/
this.removeThreadLocal();
Object o = redisTemplate.opsForValue().get(key);
if (o == null) {
return;
}
}
boolean delKey = (boolean) o;
if (delKey) {
redisTemplate.delete(key);
log.info("[idempotent]:has removed key={}", key);
}
private void removeThreadLocal() {
REDIS_KEY.remove();
}
}