AOP實現防止接口重復提交


項目中對於狀態變更接口存在重復提交的問題。

 

package com.yxx.survey.foundation.aop;

import com.alibaba.fastjson.JSON;
import com.yxx.survey.foundation.exception.ErrorEnum;
import com.yxx.survey.foundation.exception.excetion.BusinessException;
import com.yxx.survey.foundation.redis.RedisService;
import com.yxx.survey.foundation.util.encryption.HashUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {
    @Resource
    private RedisService redisService;

    @Pointcut("@annotation(RepeatSubmitCheck)")
    public void requestPointcut() {
    }

    @Before("requestPointcut() && @annotation(repeatSubmitCheck)")
    public void aroundCheck(JoinPoint joinPoint, RepeatSubmitCheck repeatSubmitCheck) {
        String className = joinPoint.getTarget().getClass().getName();

        String methodName = joinPoint.getSignature().getName();

        Object[] args = joinPoint.getArgs();
        String paramsJsonStr = JSON.toJSONString(args);

        String srcStr = className + "_" + methodName + "_" + paramsJsonStr;
        log.info(srcStr);

        String signStr = HashUtil.MD5(srcStr);

        if (!redisService.setIfNotExists(signStr, "1", repeatSubmitCheck.keepSeconds())) {
            throw BusinessException.with(ErrorEnum.INTERFACE_INVOKE_FREQUENTLY);
        }
    }
}
package com.yxx.survey.foundation.aop;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmitCheck {
    int keepSeconds() default 1;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM