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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
| package com.yeshimin.yeahboot.flowcontrol.ratelimit;
import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
@Slf4j @Component public class RateLimitInterceptor implements HandlerInterceptor {
private static final ExpressionParser PARSER = new SpelExpressionParser(); private static final StandardEvaluationContext CONTEXT = new StandardEvaluationContext();
private final Map<String, SlidingWindow> plainHolder = new ConcurrentHashMap<>(); private final Map<String, ConcurrentHashMap<String, Long>> outerGroupHolder = new ConcurrentHashMap<>(); private final Map<String, ConcurrentHashMap<String, SlidingWindow>> innerGroupHolder = new ConcurrentHashMap<>();
private static final long CLEAN_INTERVAL_MS = 5 * 60 * 1000; private static final long GROUP_EXPIRE_MS = 10 * 60 * 1000;
@Autowired(required = false) private RateLimitService rateLimitService;
@PostConstruct public void init() { log.debug("init [yeah-boot] rate limit interceptor..."); }
private static final ScheduledExecutorService CLEANER = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "RateLimitCleaner"); t.setDaemon(true); return t; });
public RateLimitInterceptor() { CLEANER.scheduleAtFixedRate(this::cleanExpiredGroups, CLEAN_INTERVAL_MS, CLEAN_INTERVAL_MS, TimeUnit.MILLISECONDS); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { log.debug("Not a method handler, skip"); return true; }
HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); RateLimit rateLimit = method.getAnnotation(RateLimit.class);
if (rateLimit == null || !rateLimit.enabled()) { log.debug("No rate limit annotation or disabled, skip"); return true; }
RateLimitConf rlConf = this.getRateLimitConf(rateLimit, method, request); log.debug("rlConf: {}", rlConf); if (rlConf.isSkip()) { log.debug("Skip rate limit, skip"); return true; }
SlidingWindow plainWindow = null; if (rlConf.getLimitCount() > -1) { log.debug("check for [limitCount]");
plainWindow = plainHolder.computeIfAbsent(rlConf.getResName(), k -> new SlidingWindow(rlConf, "[limitCount]")); log.debug("plainWindow: {}", plainWindow);
boolean allowed = plainWindow.tryAcquire(rlConf.getLimitCount(), rlConf.getReqTime()); if (!allowed) { log.debug("Rate limit exceeded: limitCount"); response.setStatus(429); response.getWriter().write("Rate limit exceeded: limitCount"); return false; } }
ConcurrentHashMap<String, Long> outerGroupMap = null; if (rlConf.getLimitGroup() > -1) { log.debug("check for [limitGroup]"); outerGroupMap = outerGroupHolder.computeIfAbsent(rlConf.getResName(), k -> new ConcurrentHashMap<>());
outerGroupMap.entrySet().removeIf(entry -> { long reqTime = entry.getValue(); if (reqTime < rlConf.getWindowFrom()) { log.debug("Remove expired group:{}, windowFrom: {}, reqTime: {}", entry.getKey(), rlConf.getWindowFrom(), reqTime); return true; } return false; });
boolean allowed; if (outerGroupMap.containsKey(rlConf.getGroupName())) { allowed = outerGroupMap.size() <= rlConf.getLimitGroup(); } else { allowed = outerGroupMap.size() + 1 <= rlConf.getLimitGroup(); }
if (!allowed) { log.debug("Rate limit exceeded: limitGroup"); response.setStatus(429); response.getWriter().write("Rate limit exceeded: limitGroup"); return false; } }
SlidingWindow innerGroupWindow = null; if (rlConf.getLimitGroupCount() > -1) { log.debug("check for [limitGroupCount]");
ConcurrentHashMap<String, SlidingWindow> map = innerGroupHolder.computeIfAbsent(rlConf.getResName(), k -> new ConcurrentHashMap<>()); innerGroupWindow = map.computeIfAbsent(rlConf.getGroupName(), k -> new SlidingWindow(rlConf, "[limitGroupCount]")); log.debug("innerGroupWindow: {}", innerGroupWindow);
boolean allowed = innerGroupWindow.tryAcquire(rlConf.getLimitGroupCount(), rlConf.getReqTime());
if (!allowed) { log.debug("Rate limit exceeded: limitGroupCount"); response.setStatus(429); response.getWriter().write("Rate limit exceeded: limitGroupCount"); return false; } }
if (rlConf.getLimitCount() > -1) { log.debug("Record request for [limitCount]"); Objects.requireNonNull(plainWindow).increase(rlConf.getReqTime()); } if (rlConf.getLimitGroup() > -1) { log.debug("Record request for [limitGroup]"); Objects.requireNonNull(outerGroupMap).put(rlConf.getGroupName(), rlConf.getReqTime()); } if (rlConf.getLimitGroupCount() > -1) { log.debug("Record request for [limitGroupCount]"); Objects.requireNonNull(innerGroupWindow).increase(rlConf.getReqTime()); }
return true; }
private RateLimitConf getRateLimitConf(RateLimit rl, Method m, HttpServletRequest req) { RateLimitConf conf = new RateLimitConf(); conf.setEnabled(rl.enabled()); conf.setName(rl.name()); conf.setGroupType(rl.groupType()); conf.setCustomGroup(rl.customGroup()); conf.setLimitCount(rl.limitCount()); conf.setLimitGroup(rl.limitGroup()); conf.setLimitGroupCount(rl.limitGroupCount()); conf.setTimeWindow(rl.timeWindow()); conf.setBucketSize(rl.bucketSize()); conf.setDynamicTimeWindow(rl.dynamicTimeWindow()); conf.setGlobal(rl.global());
if (conf.getLimitCount() < -1) { conf.setLimitCount(-1); } if (conf.getLimitGroup() < -1) { conf.setLimitGroup(-1); } if (conf.getLimitGroupCount() < -1) { conf.setLimitGroupCount(-1); }
conf.setReqTime(System.currentTimeMillis());
if (conf.getTimeWindow() < 1000) { conf.setTimeWindow(1000); } if (conf.getBucketSize() < 100) { conf.setBucketSize(100); }
this.calcWindowTimeRange(conf);
conf.setResName(this.getResName(conf, m)); conf.setGroupName(this.getGroupName(conf, m, req));
return conf; }
private void calcWindowTimeRange(RateLimitConf rlConf) { if (rlConf.isDynamicTimeWindow()) { rlConf.setWindowFrom(rlConf.getReqTime() - rlConf.getTimeWindow()); rlConf.setWindowTo(rlConf.getReqTime()); } else { rlConf.setWindowFrom(rlConf.getReqTime() / rlConf.getTimeWindow() * rlConf.getTimeWindow()); rlConf.setWindowTo(rlConf.getWindowFrom() + rlConf.getTimeWindow()); } }
private String getResName(RateLimitConf rlConf, Method m) { return rlConf.getName() == null || rlConf.getName().trim().isEmpty() ? m.getDeclaringClass().getName() + "." + m.getName() : rlConf.getName(); }
private static class SlidingWindow { private final int windowSizeMs; private final int bucketSizeMs; private final int bucketCount; private final AtomicInteger[] buckets; private volatile long lastUpdateTime; private volatile long lastGlobalBucketIndex;
@Getter @Setter private volatile long lastReqTime;
private String logFlag;
public SlidingWindow(RateLimitConf rlConf, String logFlag) { this.windowSizeMs = rlConf.getTimeWindow(); this.bucketSizeMs = rlConf.getBucketSize(); this.bucketCount = this.windowSizeMs / this.bucketSizeMs; this.buckets = new AtomicInteger[bucketCount]; for (int i = 0; i < bucketCount; i++) { buckets[i] = new AtomicInteger(0); } this.lastUpdateTime = System.currentTimeMillis(); this.lastGlobalBucketIndex = lastUpdateTime / this.bucketSizeMs;
this.lastReqTime = System.currentTimeMillis();
this.logFlag = logFlag; }
public synchronized boolean tryAcquire(int limitCount, long reqTime) { this.setLastReqTime(reqTime); this.slideWindow(reqTime);
if (limitCount >= 0 && this.calcTotalCount() >= limitCount) { return false; } return true; }
public void increase(long reqTime) { int index = (int) ((reqTime / bucketSizeMs) % bucketCount); buckets[index].incrementAndGet(); log.debug("{} buckets: {}", logFlag, Arrays.toString(buckets)); }
private void slideWindow(long reqTime) { long globalBucketIndex = reqTime / bucketSizeMs; long globalBucketsPassed = globalBucketIndex - lastGlobalBucketIndex;
log.debug("{} slideWindow: reqTime={}, globalBucketIndex={}, globalBucketsPassed={}, lastGlobalBucketIndex={}", logFlag, reqTime, globalBucketIndex, globalBucketsPassed, lastGlobalBucketIndex);
if (globalBucketsPassed <= 0) { log.debug("{}, no need to slide", logFlag); return; }
if (globalBucketsPassed >= bucketCount) { log.debug("{} clear all", logFlag); for (AtomicInteger b : buckets) { b.set(0); } } else { for (int i = 1; i <= globalBucketsPassed; i++) { int index = (int) ((lastGlobalBucketIndex + i) % bucketCount); log.debug("{} clear index: {}", logFlag, index); buckets[index].set(0); } }
lastUpdateTime = reqTime; lastGlobalBucketIndex = reqTime / bucketSizeMs; log.debug("{} slideWindow: lastUpdateTime={}, lastGlobalBucketIndex={}", logFlag, lastUpdateTime, lastGlobalBucketIndex); }
private int calcTotalCount() { int total = 0; for (AtomicInteger b : buckets) { total += b.get(); } return total; } }
private void cleanExpiredGroups() { long now = System.currentTimeMillis();
try { log.debug("[RateLimitCleaner] 开始清理过期 group... now={}", now);
innerGroupHolder.forEach((resName, groupMap) -> { for (Map.Entry<String, SlidingWindow> entry : groupMap.entrySet()) { String group = entry.getKey(); SlidingWindow window = entry.getValue();
long lastReq = window.getLastReqTime(); boolean expired = (now - lastReq > GROUP_EXPIRE_MS) && (now - lastReq > window.windowSizeMs); log.debug("[RateLimitCleaner] group={} (resName={}) lastReq={}, expiredMs={}, GROUP_EXPIRE_MS={}, windowSizeMs={}", group, resName, lastReq, now - lastReq, GROUP_EXPIRE_MS, window.windowSizeMs); if (expired) { boolean removed = groupMap.remove(group, window); if (removed) { log.debug("[RateLimitCleaner] 已清理 group={} (resName={}) lastReq={}, expiredMs={}", group, resName, lastReq, now - lastReq); } } } });
} catch (Exception e) { log.error("[RateLimitCleaner] 清理异常", e); } }
private String getGroupName(RateLimitConf rlConf, Method m, HttpServletRequest request) { switch (rlConf.getGroupType()) { case IP: return request.getRemoteAddr(); case CUSTOM: return this.getCustomGroupName(rlConf.getCustomGroup(), request, m); case NONE: default: return String.valueOf(rlConf.getWindowFrom()); } }
private String getCustomGroupName(String customGroup, HttpServletRequest request, Method method) { if (customGroup == null || customGroup.trim().isEmpty()) { log.warn("自定义分组名称不能为空"); throw new RuntimeException("自定义分组名称不能为空"); }
if (!customGroup.trim().startsWith("#")) { return customGroup; }
try { CONTEXT.setVariable("request", request); CONTEXT.setVariable("method", method);
CONTEXT.setVariable("rls", rateLimitService);
Object val = PARSER.parseExpression(customGroup).getValue(CONTEXT); if (val == null) { log.warn("解析分组名称失败"); throw new RuntimeException("解析分组名称失败"); } log.debug("SpEL 解析分组名称成功:{}", val); return String.valueOf(val); } catch (Exception e) { log.warn("SpEL 解析分组名称失败"); throw new RuntimeException("解析分组名称失败"); } } }
|