【问题标题】:Bottleneck does not seem to actually rate-limit requests?瓶颈似乎并没有实际限制请求?
【发布时间】:2021-04-28 06:32:36
【问题描述】:

我正在编写一个程序,它需要遍历多个项目,依次对每个项目执行 HTTP GET 请求。 HTTP GET 请求被第三方 API 限制为每分钟最多 5 个请求。我正在尝试使用瓶颈来限制我对这个 API 的请求,但收效甚微。

我的问题的最小示例如下:

// index.ts
import * as API from "./lib/API";

(async () => {
  try {
    //Gather all requests
    const list_of_requests = await API.Requests.get_list_of_all_requests(...);

    // Fire off each request at the appropriate rate
    list_of_requests.forEach(async (request) => {
      try {
        const request_result = await API.ResultGetter.get_result(...);

      } catch (error) {
        console.log(error.message);
      }
    });
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
})();

在我的./lib/API

// API.ts
import { AxiosRequestConfig } from "axios";
import { scheduleRequest } from "../util/Limiter";

export async function ResultGetter(...) {
     const requestURL: string = "https://www.website.ext/...";

  const requestConfig: AxiosRequestConfig = {
    url: requestURL,
    method: "GET",
    responseType: "json",
  };

return await scheduleRequest(requestConfig);
}

最后,在我的util/Limiter

// Limiter.ts
import Bottleneck from "bottleneck";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";

/*
5 API requests per minute; 500 API requests per day
*/
export const limiter = new Bottleneck({
  reservoir: 500, 
  reservoirRefreshAmount: 500,
  reservoirRefreshInterval: 24 * 60 * 60 * 1000,
  maxConcurrent: 1,
  mintime: Math.ceil(1 / (5 / 60 / 1000)),
});

export async function scheduleRequest(
  request: AxiosRequestConfig
): Promise<AxiosResponse<any>> {
  return limiter.schedule(() => axios(request));
}

但是,当我实际使用这个程序时,请求会以最快的速度触发。我真的不确定在这种情况下我缺少什么。据我了解,limiter.schedule(...) 应该返回一个在请求发生时解决的承诺,受设置的速率限制的限制。但这不是这里发生的事情。

【问题讨论】:

    标签: javascript node.js typescript rate-limiting bottleneck


    【解决方案1】:

    事实证明这是一个很难找到的错字。

    在我的原始代码中,我有以下内容来定义我的速率限制器:

    export const limiter = new Bottleneck({
      reservoir: 500, 
      reservoirRefreshAmount: 500,
      reservoirRefreshInterval: 24 * 60 * 60 * 1000,
      maxConcurrent: 1,
      mintime: Math.ceil(1 / (5 / 60 / 1000)),
    });
    

    好吧,我写了mintime 而不是minTime 大写的T,这一事实让世界变得与众不同。

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2019-01-11
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 2013-04-08
      • 2011-01-26
      • 2012-01-12
      • 2015-11-05
      相关资源
      最近更新 更多