>  기사  >  웹 프론트엔드  >  spring-aop이 네트워크 요청의 반복 제출을 방지하는 방법

spring-aop이 네트워크 요청의 반복 제출을 방지하는 방법

坏嘻嘻
坏嘻嘻원래의
2018-09-14 15:03:461783검색

구체적인 원리는 매우 간단합니다. spring-aop의 서라운드 알림을 통해 요청 매개변수가 이미 존재하는지 확인하기 위해 변환됩니다. 그렇지 않으면 오류가 발생합니다. 요청 완료 후 저장 및 삭제됩니다.

구체적인 코드는 다음과 같습니다.
1. Annotation @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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.