You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.4 KiB

  1. package com.example.demo.config;
  2. import com.google.common.cache.Cache;
  3. import com.google.common.cache.CacheBuilder;
  4. import java.util.concurrent.TimeUnit;
  5. /**
  6. * 本地限流工具类基于Guava Cache
  7. */
  8. public class RateLimitUtil {
  9. // 缓存:key=限流标识(用户ID/IP),value=占位符(无实际意义)
  10. private static final Cache<String, Object> RATE_LIMIT_CACHE = CacheBuilder.newBuilder()
  11. .expireAfterWrite(3, TimeUnit.SECONDS) // 3秒后自动过期(时间窗口)
  12. .maximumSize(5000) // 最大缓存容量(防止内存溢出,根据用户量调整)
  13. .build();
  14. /**
  15. * 判断是否允许请求
  16. * @param key 限流唯一标识如用户IDIP
  17. * @return true=允许请求false=限流中
  18. */
  19. public static boolean isAllowed(String key) {
  20. // 1. 尝试从缓存获取key,存在则说明3秒内已请求过(限流)
  21. if (RATE_LIMIT_CACHE.getIfPresent(key) != null) {
  22. return false;
  23. }
  24. // 2. 缓存中不存在,存入缓存(占位符用new Object()即可)
  25. RATE_LIMIT_CACHE.put(key, new Object());
  26. return true;
  27. }
  28. /**
  29. * 手动移除限流标识如接口执行失败时释放限流
  30. * @param key 限流唯一标识
  31. */
  32. public static void removeKey(String key) {
  33. RATE_LIMIT_CACHE.invalidate(key);
  34. }
  35. }