ip 请求次数限制8

This commit is contained in:
GYJ
2025-03-23 22:00:52 +08:00
parent de561f5626
commit d24c89922a

View File

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