PersionalRateLimitService.java 1.86 KB
package com.yoho.search.aop.downgrade;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class PersionalRateLimitService {

    private static final Logger DOWNGRADE = LoggerFactory.getLogger("DOWNGRADE");

    private Map<String, KeyCountWithExpiredTime> keyCountMap = new ConcurrentHashMap<String, KeyCountWithExpiredTime>();

    private Map<String, Integer> oldCountMap = new ConcurrentHashMap<String, Integer>();

    public boolean isPersionalRateLimit(String rateLimitName, PersionalRateLimitConfig limitConfig) {
        try {
            long expireTime = System.currentTimeMillis() + limitConfig.getSecond() * 1000L;
            KeyCountWithExpiredTime keyCountWithExpiredTime = keyCountMap.putIfAbsent(rateLimitName, new KeyCountWithExpiredTime(expireTime));
            if (keyCountWithExpiredTime == null) {
                keyCountWithExpiredTime = keyCountMap.get(rateLimitName);
            }
            int currentCount = keyCountWithExpiredTime.incrementAndGet(expireTime);
            Integer oldCount = oldCountMap.get(rateLimitName);
            //第二轮再开始打上一轮降级日志
            if (currentCount == 1 && oldCount != null) {
                DOWNGRADE.error("PersionalRateLimit happen ,rateLimitName is [{}], oldCount is[{}], limitConfig is [{}]", rateLimitName,oldCount, limitConfig.toLogInfo());
                oldCountMap.remove(rateLimitName);
            }
            if (currentCount <= limitConfig.getLimit()) {
                return false;
            }
            oldCountMap.put(rateLimitName, currentCount);
            return true;
        }catch (Exception e){
            DOWNGRADE.error(e.getMessage(),e);
            return false;
        }
    }

}