具体代码如下:
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防止重复提交网络请求的详细内容。
