ReSubmitAspect.java 2.0 KB
package com.tianbo.analysis.annotation;


import com.alibaba.fastjson.JSONObject;
import com.tianbo.analysis.controller.bean.ResponseReason;
import com.tianbo.analysis.model.ResultJson;
import com.tianbo.analysis.tools.ResubmitLock;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class ReSubmitAspect {

    private final static String DATA = "data";
    private final static Object PRESENT = new Object();

    @Around("@annotation(com.tianbo.analysis.annotation.ReSubmitCheck)")
    public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取注解信息
        ReSubmitCheck annotation = method.getAnnotation(ReSubmitCheck.class);
        int delaySeconds = annotation.delaySeconds();
        Object[] pointArgs = joinPoint.getArgs();
        String key = "";
        //获取第一个参数
        Object firstParam = pointArgs[0];
        //解析参数
        if (firstParam != null) {
            //生成加密参数 使用了content_MD5的加密方式
            key = ResubmitLock.handleKey(JSONObject.toJSONString(firstParam));
        }

        //执行锁
        boolean lock = false;
        try {
            //设置解锁key
            lock = ResubmitLock.getInstance().lock(key, PRESENT);
            if (lock) {
                //放行
                return joinPoint.proceed();
            } else {
                //响应重复提交异常
                return new ResultJson(ResponseReason.REAPET_SUBMIT_ERR);
            }
        } finally {
            //设置解锁key和解锁时间
            ResubmitLock.getInstance().unLock(lock, key, delaySeconds);
        }
    }
}