package com.jiayue.ssi.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
* 接口访问限制工具类
*
* @author xsl
* @since 2023/02/24
*/
public class InterfaceLimitUtil {
    private static ConcurrentHashMap<String, Integer> interfaceLimitMap = new ConcurrentHashMap<>();

    /**
     * 接口检测*
     * @param request
     * @param time 限制时间 单位：毫秒
     * @param value 允许请求的次数
     * @return boolean true:允许通过 false:不通过
     */
    public synchronized static boolean checkInterface(HttpServletRequest request,long time,int value){
        Integer uCount = 0;
        if (LocalCache.get(request.getRequestURI())==null){
            // 首次访问
            LocalCache.set(request.getRequestURI(),request.getRequestURI(),time);
        }
        else{
            uCount = interfaceLimitMap.get(request.getRequestURI());
        }
        if (uCount >= value) { // 超过次数，不执行目标方法
            Iterator<Map.Entry<String, Integer>> countMap = interfaceLimitMap.entrySet().iterator();
            while (countMap.hasNext()) {
                Map.Entry<String, Integer> entry = countMap.next();
                String requestURI = entry.getKey();
                if (requestURI.equals(request.getRequestURI())){
                    countMap.remove();
                }
            }
            return false;
        } else { // 未超过次数， 记录加一
            interfaceLimitMap.put(request.getRequestURI(),uCount + 1);
        }
        return true;
    }
}
