具體原理很簡單,通過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
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com