手揣网教程:绿色安全纯净官方版,体验当今速度最快的浏览器!

如何spring-aop防范重复提交网络请求

时间:2024/12/6作者:未知来源:手揣网教程人气:

[摘要]具体原理很简单,通过spring-aop的环绕通知,请求开始时将请求参数转换校验是否已存在,已存在则报错,否则存储,请求完成后删除。具体代码如下: 1、注释@interfacepackage com...

具体原理很简单,通过spring-aop的环绕通知,请求开始时将请求参数转换校验是否已存在,已存在则报错,否则存储,请求完成后删除。

具体代码如下:
1、注释@interface

package com.yuntu.commons.intelligent.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/**
 * Created by niuzy on 2018-09-13.
 */@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface NotDuplicate {}

2、spring切面和环绕通知

import com.yuntu.commons.ServiceException;import com.yuntu.commons.intelligent.ExceptionConstants;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import java.lang.reflect.Method;import java.util.Set;import java.util.concurrent.ConcurrentSkipListSet;/**
 * Created by niuzy on 2018-09-13.
 */@Aspect@Componentpublic class NotDuplicateAop {
    private Logger LOG = LoggerFactory.getLogger(NotDuplicateAop.class);    private static final Set<String> KEY =  new ConcurrentSkipListSet<>();    @Pointcut("@annotation(com.yuntu.commons.intelligent.annotation.NotDuplicate)")    public void duplicate() {
    }    /**
     * 对方法拦截后进行参数验证
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("duplicate()")    public Object duplicate(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature msig = (MethodSignature) pjp.getSignature();
        Method currentMethod = pjp.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());        //拼接签名
        StringBuilder sb = new StringBuilder(currentMethod.toString());
        Object[] args = pjp.getArgs();        for (Object object : args) {            if(object != null){
                sb.append(object.getClass().toString());
                sb.append(object.toString());
            }
        }
        String sign = sb.toString();        boolean success = KEY.add(sign);        if(!success){            throw new ServiceException(ExceptionConstants.ILLEGAL_REQUEST_EXCEPTION,"该方法正在执行,不能重复请求");
        }        try {            return pjp.proceed();
        } finally {
            KEY.remove(sign);
        }

    }
}

3、使用:
在需要的方法上添加@NotDuplicate

相关推荐:

Spring管理MongoDB

Mongodb整合Spring示例

以上就是如何spring-aop防止重复提交网络请求的详细内容,更多请关注php中文网其它相关文章!


网站建设是一个广义的术语,涵盖了许多不同的技能和学科中所使用的生产和维护的网站。



关键词:如何spring-aop防范重复提交网络请求




Copyright © 2012-2018 手揣网教程(http://www.shouchuai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版