AiLimitUtil.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package jnpf.util;
  2. import cn.hutool.cache.CacheUtil;
  3. import cn.hutool.cache.impl.TimedCache;
  4. import jnpf.config.AiProperties;
  5. import java.util.concurrent.atomic.AtomicInteger;
  6. /**
  7. * AI接口限流
  8. *
  9. * @author JNPF开发平台组
  10. * @copyright 引迈信息技术有限公司
  11. * @date 2025/3/7 10:00
  12. */
  13. public class AiLimitUtil {
  14. private static AiProperties aiProperties;
  15. private static TimedCache<String, AtomicInteger> limit = null;
  16. private static final String TOTAL_KEY = "ai_limit_total";
  17. public AiLimitUtil(AiProperties aiProperties) {
  18. AiLimitUtil.aiProperties = aiProperties;
  19. if (limit == null) {
  20. limit = CacheUtil.newTimedCache(aiProperties.getUserLimitTime().toMillis());
  21. // 一分钟清理一次无用数据
  22. limit.schedulePrune(1000L * 60);
  23. }
  24. }
  25. /**
  26. * 是否可以请求
  27. * @param userId
  28. * @return
  29. */
  30. public static boolean tryAcquire(String userId) {
  31. if(limit == null) {
  32. return true;
  33. }
  34. if (StringUtil.isNotEmpty(userId)) {
  35. // 按用户限制
  36. AtomicInteger userCount = limit.get(userId, false, AtomicInteger::new);
  37. if (userCount.incrementAndGet() > aiProperties.getUserLimitCount()) {
  38. return false;
  39. }
  40. }
  41. // 所有请求限制
  42. AtomicInteger totalCount = limit.get(TOTAL_KEY, false, aiProperties.getTotalLimitTime().toMillis(), AtomicInteger::new);
  43. return totalCount.incrementAndGet() <= aiProperties.getTotalLimitCount();
  44. }
  45. }