Browse Source

请求限流

Michael Wang 3 years ago
parent
commit
29000981e0
2 changed files with 61 additions and 0 deletions
  1. 3 0
      src/constants/constants.ts
  2. 58 0
      src/utils/tryLimit.ts

+ 3 - 0
src/constants/constants.ts

@@ -2,3 +2,6 @@ export const YYYYMMDDHHmmss = "YYYY-MM-DD HH:mm:ss";
 
 
 export const VITE_SLS_STORE_NAME = import.meta.env
 export const VITE_SLS_STORE_NAME = import.meta.env
   .VITE_SLS_STORE_NAME as string;
   .VITE_SLS_STORE_NAME as string;
+
+/** 限流请求的服务器 */
+export const LIMIT_SERVER = "https://tcc.qmth.com.cn";

+ 58 - 0
src/utils/tryLimit.ts

@@ -0,0 +1,58 @@
+import { LIMIT_SERVER } from "@/constants/constants";
+import axios from "axios";
+
+/** 是否对请求限流 */
+export async function tryLimit({
+  action,
+  limit = 100,
+}: {
+  action: string;
+  limit: number;
+}) {
+  let res = null;
+  let serverPass = false;
+  try {
+    res = await axios.get(
+      `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
+      { timeout: 10 * 1000 }
+    );
+    serverPass = res.data.pass;
+
+    logger({
+      key: "请求限流",
+      act: "第一次限流调用",
+      dtl: serverPass ? "进入" : "限流",
+      ext: { limitAction: action },
+    });
+    if (!serverPass) {
+      // 休眠 1 ~ 5 秒 再试
+      res = null; // 供外部判断
+
+      const sleepTime = Math.random() * 4 + 1;
+      console.log({ sleepTime, now: Date.now() });
+      await new Promise((resolve) => setTimeout(resolve, sleepTime * 1000));
+      console.log({ sleepTime, now: Date.now() });
+      res = await axios.get(
+        `${LIMIT_SERVER}/rate_limit/prod/${action}/${limit}`,
+        { timeout: 10 * 1000 }
+      );
+      serverPass = res.data.pass;
+      logger({
+        key: "请求限流",
+        act: "限流后自动重试",
+        dtl: serverPass ? "进入" : "依然限流",
+        ext: { limitAction: action },
+      });
+    }
+  } catch (error) {
+    console.log(error);
+    logger({
+      key: "请求限流",
+      act: "限流请求失败",
+      ejn: JSON.stringify(error),
+      ext: { limitAction: action },
+    });
+  }
+
+  return { limitResult: serverPass, serverOk: !!res };
+}