Redisson幂等校验例子

在添加接口增加幂等校验, 防止用户在短时间内重复调用添加接口

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();
  }
}

posted @   剑阁丶神灯  阅读(81)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示