ip 请求次数限制8
This commit is contained in:
parent
de561f5626
commit
d24c89922a
|
|
@ -3,6 +3,9 @@ package com.sqx.common.aspect;
|
|||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author GYJoker
|
||||
|
|
@ -20,38 +23,34 @@ public class IpAccessCounter {
|
|||
|
||||
static {
|
||||
// 定时任务,每分钟清理一次访问记录
|
||||
Timer timer = new Timer();
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
log.info("IpAccessCounter 清理启动,定时任务启动");
|
||||
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
|
||||
executor.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
|
||||
// 用于记录移除的 IP 集合
|
||||
Set<String> removedIps = new HashSet<>();
|
||||
for (Map.Entry<String, List<Long>> entry : IP_ACCESS_TIMES.entrySet()) {
|
||||
String ip = entry.getKey();
|
||||
List<Long> accessTimes = entry.getValue();
|
||||
IP_ACCESS_TIMES.forEach((ip, accessTimes) -> {
|
||||
accessTimes.removeIf(time -> currentTime - time > ONE_MINUTE);
|
||||
if (accessTimes.isEmpty()) {
|
||||
removedIps.add(ip);
|
||||
}
|
||||
}
|
||||
});
|
||||
removedIps.forEach(IP_ACCESS_TIMES::remove);
|
||||
|
||||
Set<String> removedBlacklistIps = new HashSet<>();
|
||||
for (Map.Entry<String, Long> entry : BLACKLIST.entrySet()) {
|
||||
String ip = entry.getKey();
|
||||
long addedTime = entry.getValue();
|
||||
if (currentTime - addedTime > TEN_MINUTES) {
|
||||
removedBlacklistIps.add(ip);
|
||||
BLACKLIST.entrySet().removeIf(entry -> {
|
||||
boolean shouldRemove = currentTime - entry.getValue() > TEN_MINUTES;
|
||||
if (shouldRemove) {
|
||||
removedBlacklistIps.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
removedBlacklistIps.forEach(BLACKLIST::remove);
|
||||
return shouldRemove;
|
||||
});
|
||||
|
||||
log.info("IpAccessCounter 清理完成,移除了 {} 个 IP 的黑名单记录,当前 BLACKLIST 大小: {}, IP_ACCESS_TIMES 大小: {}",
|
||||
removedBlacklistIps.size(), BLACKLIST.size(), IP_ACCESS_TIMES.size());
|
||||
} catch (Exception e) {
|
||||
log.error("定时任务异常", e);
|
||||
}
|
||||
}, ONE_MINUTE, 20000);
|
||||
}, ONE_MINUTE, 20000, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
// 检查 IP 是否可以访问
|
||||
|
|
|
|||
Loading…
Reference in New Issue