diff --git a/src/main/java/com/sqx/common/aspect/IpAccessCounter.java b/src/main/java/com/sqx/common/aspect/IpAccessCounter.java index 6b226640..ff1710f6 100644 --- a/src/main/java/com/sqx/common/aspect/IpAccessCounter.java +++ b/src/main/java/com/sqx/common/aspect/IpAccessCounter.java @@ -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 removedIps = new HashSet<>(); - for (Map.Entry> entry : IP_ACCESS_TIMES.entrySet()) { - String ip = entry.getKey(); - List 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 removedBlacklistIps = new HashSet<>(); - for (Map.Entry 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 是否可以访问