1、创建 SubmitLock 注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubmitLock {String key() default "";
}
2、注解实现
@Autowiredpublic RedisUtils redisUtils;@Around("execution(* com.example.code_generation..*Controller.*(..)) && @annotation(lock)")public Object submitInterceptor(ProceedingJoinPoint pjp, SubmitLock lock) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String uri = request.getRequestURI();MethodSignature signature = (MethodSignature) pjp.getSignature();Method method = signature.getMethod();//真实类名字String targetName = pjp.getTarget().getClass().getName();//真实方式String methodName = pjp.getSignature().getName();//所有的请求参数Object[] arguments = pjp.getArgs();Object[] args = new Object[arguments.length];SubmitLock localLock = method.getAnnotation(SubmitLock.class);String key = setKey(localLock.key(), pjp.getArgs());if (!StringUtils.isEmpty(key)) {if (redisUtils.get(key) != null) {log.error("请勿重复操作,uri = 【{}】", uri);return new RspData<>(BizCodeEnum.WARN, "请勿重复操作");}redisUtils.set(key,key,2);}Object result = null;try {result = pjp.proceed();return result;}catch (Throwable throwable){throw new RuntimeException("服务器异常");}finally {int order = 0;for (Object arg : arguments){if (arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof MultipartFile){continue;}args[order] = arg;order ++ ;}log.info("调用Controller方法返回结果,targetName = {}, methodName = {}, args = {}, result = {}",targetName, methodName, args, result);}}private String setKey(String keyExpress, Object[] args) {if (null != args && args.length > 0) {keyExpress = keyExpress.replace("arg[0]", args[0].toString());}return keyExpress;}
3、controller 测试验证
@SubmitLock(key = "getTest")@ApiOperation(value = "获取代办任务")@GetMapping("getTest")public Object getTest(@CurrentUser UserInfo userInfo) {}