赞
踩
在开发过程中总会出现重复提交,产生多条数据的误操作操作,通过自定义注解的方式防止重复提交,具体代码如下:
限制每个请求每十秒钟只能提交一次,以上参数都是可以调整的
具体代码:
注解类
@Target(ElementType.METHOD)//方法注解
@Retention(RetentionPolicy.RUNTIME)//注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
public @interface NoRepeatSubmit {
}
注解类实现类 @Aspect @Configuration @Slf4j @Component public class NoRepeatSubmitAop { private final static String createWorkflowTemplate = "createWorkflowTemplate"; private final static String startUpTask = "startUpTask"; @Autowired DataService dataService; @Around("execution(* xxx.xx.controller.*.*(..)) && @annotation(nrs)") public Object around(ProceedingJoinPoint joinPoint, NoRepeatSubmit nrs) throws Throwable { String key = getFieldsNameValueMap(joinPoint); log.info("查询缓存的内容为:{}", key); if (!dataService.isExistsCluster(key)) { Object o = joinPoint.proceed(); dataService.getClusterCacheService().setObject(key, "1", 10, TimeUnit.SECONDS); return o; } else { log.error("验证重复提交!", key); return BaseResponse.fail(NativeSphereWorkflowCodeEnum.RECOMMIT.getCode(), NativeSphereWorkflowCodeEnum.RECOMMIT.getMessage()); } } //把请求地址信息缓存起来方面下次请求进行判断 public static String getFieldsNameValueMap(ProceedingJoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); String methodName = joinPoint.getSignature().getName(); DigestUtils.md5(args.toString()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String key = request.getServletPath(); if (methodName.equals(createWorkflowTemplate)) { key = String.join("_", request.getServletPath(), ((CreateWorkflowTemplateReq) args[0]).getTemplateVersionId()); } if (methodName.equals(startUpTask)) { key = String.join("_", request.getServletPath(), ((StartUpWorkflowTaskReq) args[0]).getTemplateVersionId()); } return key; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。