tryLimit.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { LIMIT_SERVER } from "@/constants/constants";
  2. import axios from "axios";
  3. /** 是否对请求限流 */
  4. export async function tryLimit({
  5. action,
  6. limit = 100,
  7. }: {
  8. action: string;
  9. limit: number;
  10. }) {
  11. let res = null;
  12. let serverPass = false;
  13. try {
  14. res = await axios.get(
  15. `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
  16. { timeout: 10 * 1000 }
  17. );
  18. serverPass = res.data.pass;
  19. logger({
  20. key: "请求限流",
  21. act: "第一次限流调用",
  22. dtl: serverPass ? "进入" : "限流",
  23. ext: { limitAction: action },
  24. });
  25. if (!serverPass) {
  26. // 休眠 1 ~ 5 秒 再试
  27. res = null; // 供外部判断
  28. const sleepTime = Math.random() * 4 + 1;
  29. console.log({ sleepTime, now: Date.now() });
  30. await new Promise((resolve) => setTimeout(resolve, sleepTime * 1000));
  31. console.log({ sleepTime, now: Date.now() });
  32. res = await axios.get(
  33. `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
  34. { timeout: 10 * 1000 }
  35. );
  36. serverPass = res.data.pass;
  37. logger({
  38. key: "请求限流",
  39. act: "限流后自动重试",
  40. dtl: serverPass ? "进入" : "依然限流",
  41. ext: { limitAction: action },
  42. });
  43. }
  44. } catch (error) {
  45. console.log(error);
  46. logger({
  47. key: "请求限流",
  48. act: "限流请求失败",
  49. ejn: JSON.stringify(error),
  50. ext: { limitAction: action },
  51. });
  52. }
  53. return { limitResult: serverPass, serverOk: !!res };
  54. }