java接口防止用户重复请求,自定义注解+springAop

声明:以下代码为参照网上代码手敲的,只是自己加强记忆,作者出处忘记了,抱歉!

创建自定义注解

@Inherited
@Document
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.Type})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotRepeated {
}

创建AOP切面

@Aspect
@Component
@ComponentScan
@EnableAspectJAutoProxy
public class NotRepeatedAspect {

    public static final Set<String> KEY = new ConcurrentSkipListSet<>();

    //切入点
    @Pointcut("@annotation(com.smart.common.annotation.notrepeated.NotRepeated)")
    public void duplicate() {
    }

    /**
     * 对方法拦截后进行参数验证,判断是否重复提交
     * @param joinPoint
     * @return
     */
    @Around("duplicate()")
    public Object duplicate(ProceedingJoinPoint joinPoint) throws Throwable{
        //Signature 封装方法相关的信息
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature; 
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法上");
        }
        methodSignature = (MethodSignature) signature;
        //获取方法
        Method method = methodSignature.getMethod();
        StringBuilder builder = new StringBuilder(method.toString);
        //获取方法参数
        Object[] args = joinPoint.getArgs();
        for (Object object : args) {
            if (object != null) {
                builder.append(object.getClass().toString());
                builder.append(object.toString());
            }
        }
        String sign = builder.toString();
        //返回true说明该请求不是重复提交,false表示方法还在执行中
        boolean success = KEY.add(sign);
        if (!success) {
            return JsonModel.toSuccess("休息一下再点击");
        }
        try {
            joinPoint.proceed();
        } finally {
            KEY.remove(sign);
        }
        
    }
}

在需要处理的方法上加载自定义注解@NotRepeated

猜你喜欢

转载自blog.csdn.net/qq389203946/article/details/86534911