package com.ssyf.common.web.aop;

import com.ssyf.common.core.util.AssertUtil;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.common.web.helper.RequestContextHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 请求同步处理器
 * @author huwei
 * @date 2022/10/30 13:43
 */
@Aspect
@Component
public class RequestSynchronizationAop {

    private Map<String ,Object> lockerMap = new ConcurrentHashMap<>();

    /**
     * 请求方法同步
     */
    @Around("@annotation(com.ssyf.common.web.aop.RequestSynchronization)")
    public Object requestSynchronization(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StringBuilder sb = new StringBuilder();
        sb.append(RequestContextHelper.getClientIp()).append("+").append(RequestContextHelper.getContext().getRequest().getRequestURI());
        boolean isGo = getRequest(sb.toString());
        
        AssertUtil.isTrue(isGo, ServiceRuntimeException.instance(ApiCodeUser.REQUEST_PROCESSING));

        try {
            //执行请求
            Object result = proceedingJoinPoint.proceed();

            return result;
        }finally {
            //释放请求
            releaseRequest(sb.toString());
        }

    }


    /**
     * 是否请求
     * @param key
     * @return
     */
    private synchronized boolean getRequest(String key){
        if(this.lockerMap.containsKey(key)){
            return false;
        }
        this.lockerMap.put(key ,1);
        return true;
    }

    /**
     * 释放请求
     * @param key
     */
    private void releaseRequest(String key){
        this.lockerMap.remove(key);
    }

}
