注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RabbitNoRepeatSubmit {
}
实现类
@Aspect
@Component
@Slf4j
public class RabbitNoRepeatSubmitAspect {
@Autowired
RabbitRedisService rabbitRedisService;
@Autowired
RabbitAuthenticationComponent rabbitAuthenticationComponent;
@Around("execution(* com.zsxt..*Controller.*(..)) && @annotation(nrs)")
public Object arround(ProceedingJoinPoint pjp, RabbitNoRepeatSubmit nrs) {
// validator 参数检查
Object[] args = pjp.getArgs();
for (Object arg : args) {
if (arg instanceof BindingResult) {
BindingResult result = (BindingResult) arg;
if (result.hasErrors()) {
StringBuilder messageBuilder = new StringBuilder();
result.getAllErrors().forEach(err -> messageBuilder.append(err.getDefaultMessage() + ","));
return new RabbitResponse("400",
messageBuilder.toString().substring(0, messageBuilder.toString().length() - 1), null);
}
}
}
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String key = rabbitAuthenticationComponent.getUser().getUsername() + "-" + request.getServletPath();
if (!rabbitRedisService.exists(key)) {
rabbitRedisService.set(key, null, 3000L);
Object o = pjp.proceed();
return o;
} else {
log.error("重复提交");
return new RabbitResponse(RabbitResponseEnums.REAPTE_SUBMIT);
}
} catch (Throwable e) {
e.printStackTrace();
log.error("验证重复提交时出现未知异常!");
return new RabbitResponse(RabbitResponseEnums.SYS_ERROR);
}
}
}
调用
@PostMapping("/create")
@RabbitNoRepeatSubmit
public Object create(@RequestBody @Valid SystemVo vo, BindingResult result) {
boolean success = oauthSystemService.save(vo);
if (!success) {
return new RabbitResponse(RabbitResponseEnums.UPDATE_ERROR);
}
return new RabbitResponse(RabbitResponseEnums.SUCCESS);
}
|