Redisson幂等校验例子

发布时间 2023-08-28 12:35:52作者: 剑阁丶神灯
在添加接口增加幂等校验, 防止用户在短时间内重复调用添加接口

import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Order(1)
public class IdempotentAspect {
@Autowired
private RedissonClient redissonClient;
@Pointcut("@annotation(com.aexpec.cmd.common.annotation.IdempotentCheck)")
public void idempotentCheck() {
}

@Before("idempotentCheck()")
public void doBefore(JoinPoint joinPoint) {
//拿到被注解的方法签名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//拿到被注解的方法
Method method = signature.getMethod();
Object[] args = joinPoint.getArgs();
Method targetMethod = AopUtils.getMostSpecificMethod(method, joinPoint.getTarget().getClass());
IdempotentCheck idempotentCheck = AnnotationUtils.findAnnotation(targetMethod, IdempotentCheck.class);
if (null == idempotentCheck) {
throw new BizException(BaseCode.PARAM_ERROR);
}
int expireTime = idempotentCheck.expireTime();
StringBuilder key = new StringBuilder(targetMethod.getName())
.append(targetMethod.getName())
.append(ArrayUtils.toString(args, "-"));
RBucket<Object> bucket = redissonClient.getBucket(key.toString());
if (bucket.isExists()) {
throw new BizException(BaseCode.NOT_REPEAT_COMMIT);
} else {
bucket.set(AuthUtil.getUserInfo().getUserAccount(), expireTime, TimeUnit.SECONDS);
}
}
}

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IdempotentCheck {
int expireTime() default 3;
}
@RestController
@RequestMapping("/a")
public class AController {
  @PostMapping("/{modelCode}/add")
  @IdempotentCheck()
  public ApiResponse<String> add(
@PathVariable("modelCode") String modelCode,
@RequestBody Map<String, Object> params) {
  // ...
  return new ApiResponse<String>().success();
  }
}