PersionalRateLimitService.java
1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
}
}
}