SpringBootインタフェースべき乗など

2713 ワード


import com.paascloud.core.lock.RedisDistributedLock;
import com.paascloud.provider.config.annotation.Ide;
import com.paascloud.provider.config.exception.BusinessException;
import com.paascloud.wrapper.Wrapper;
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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;


@Slf4j
@Aspect
@Component
public class ReqSubmitAspect {

    @Autowired
    private RedisDistributedLock redisDistributedLock;

    @Pointcut("@annotation(com.paascloud.provider.config.annotation.Ide)")
    public void idePointCut() {
    }

    @Around("idePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Ide ide = method.getAnnotation(Ide.class);
        int lockSeconds = ide.lockTime();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();

        String key = getIdeKey(token, requestURI);

        //    
        boolean lock = redisDistributedLock.lock(key, lockSeconds);
        log.info("tryLock key = [{}]", key);

        if (lock) {
            log.info("tryLock success, key = [{}]", key);
            //      
            Object result;
            try {
                //     
                result = joinPoint.proceed();
            } finally {
                //   
                redisDistributedLock.releaseLock(key);
                log.info("releaseLock success, key = [{}]", key);
            }
            return result;
        } else {
            //      ,          
            log.info("tryLock fail, key = [{}]", key);
            throw new BusinessException(Wrapper.ERROR_CODE, "    ,     !");
        }
    }

    private String getIdeKey(String token, String requestURI) {
        return "cms:identity:" + token + requestURI;
    }


}