package com.jkcredit.invoice.component;

import cn.hutool.core.thread.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
/**
 * @Description 接口服务容器限流工具
 * @Author mashengyi
 * @Date 2022/2/8 18:13
 * @Param
 * @Return
 * @Exception
 *
 */
public class StatisRequestIdTimeComp {
    public static volatile boolean isLimit = false;
    /**
     * requestId 及 时间
     */
    public Map<String, Long> map = new ConcurrentHashMap<>();
    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1,new NamedThreadFactory("STATIC_PROCESS_POOL",false));
    /**
     * 关注的请求时间秒
     */
    private byte costTimeAtten = 3;
    private int limitCount = 200;

    public StatisRequestIdTimeComp() {
    }

    /**
     * 放入requestid 及时间
     *
     * @param requestId
     */
    public void putReQuestIdAndTime(String requestId) {
        map.put(requestId, System.currentTimeMillis());
    }

    /**
     * 放入requestid 及时间
     *
     * @param requestId
     */
    public void removeReQuestIdAndTime(String requestId) {
        map.remove(requestId);
    }

    @PostConstruct
    public void initScan() {
        log.info("StatisRequestIdTimeComp-initScan-开始轮训计数");
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                int count = 0;
                long currTime = System.currentTimeMillis();
                for (Map.Entry<String, Long> entry : map.entrySet()) {
                    if (currTime - entry.getValue() > costTimeAtten * 1000) {
                        count++;
                        log.info("耗时requestid************" + entry.getKey() + "***************" + (currTime - entry.getValue()));
                    }
                }
                isLimit = count > limitCount;
                //  log.info("当前请求数："+map.size()+"当前耗时请求数："+count+"是否限制："+isLimit);
            }
        }, 1, 1, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void destroy() {
        service.shutdown();
    }
}
