【发布时间】:2020-11-17 07:37:49
【问题描述】:
我正在尝试向BoardGameGeek (BGG) API 发出多个请求,并且在特定时间范围内发出一定数量的请求后,我超时(状态代码 429)。我已经尝试了几个库来尝试让它工作。
我尝试使用下面的simple-rate-limiter 库,但这不起作用,因为 BGG 似乎对速率限制非常激进,而且他们也没有发布官方限制。
/* simple-rate-limiter initialization (https://www.npmjs.com/package/simple-rate-limiter) */
const limit = require('simple-rate-limiter');
const request = limit(require('request')).to(10).per(1000);
const fetchStatistics = async (game) => {
/* Fetching the statistics from a separate API, because the base API doesn't include stats */
const url = 'https://cors-anywhere.herokuapp.com/https://www.boardgamegeek.com/xmlapi2/thing?id=' + game.$.objectid + '&stats=1';
request(url, (err, res, body) => { // simple-rate-limiter making the request
const xml = body;
return XML2JS.parseString(xml, (err, result) => { //XML2JS library call
console.log(result);
})
})
}
然后我尝试将 oibackoff 库与 simple-rate-limiter 结合使用,如下所示,但仍然没有成功。
/* simple-rate-limiter initialization (https://www.npmjs.com/package/simple-rate-limiter) */
const limit = require('simple-rate-limiter');
const request = limit(require('request')).to(10).per(1000);
/* oibackoff initialization (https://www.npmjs.com/package/oibackoff) */
const backoff = require('oibackoff').backoff({
algorithm: 'exponential',
delayRatio: 1,
maxTries: 0,
});
const fetchStatistics = async (game) => {
/* Fetching the statistics from a separate API, because the base API doesn't include stats */
const url = 'https://cors-anywhere.herokuapp.com/https://www.boardgamegeek.com/xmlapi2/thing?id=' + game.$.objectid + '&stats=1';
backoff(request, url, (err, res, body) => { // simple-rate-limiter making the request
console.log(res.statusCode);
const xml = res.body;
return XML2JS.parseString(xml, (err, result) => {
console.log(result);
})
})
}
我做错了吗?我应该使用不同的库/方法吗?
旁注:我也尝试了 request-rate-limiter,但我无法让语法适用于我的项目。
【问题讨论】:
-
如果您仍然得到 429,也许您只需要不断更改数字,直到不再发生这种情况。从每 10 秒 1 个请求开始,然后报告回来。
-
您可能还受到使用 cors-anywhere 服务这一事实的限制。如果有其他人通过 cors-anywhere 做同样的事情,那么你们都有相同的限制。将它用于任何严肃的事情都不是一个好主意。
-
是的,减慢请求的速度是可行的,但是对于具有约 600 个请求的集合,以该速率加载需要数小时。我对这个问题的主要担心是我是否误用了
oibackoff库。遇到 429 时它似乎并没有退缩。它只是不断地处理请求。 -
问题是,如果您或多或少找到了限制,无论如何都无法超越。即使您确实让它工作,指数退避可能会更慢。此外,您仍在与使用 cors-anywhere 的其他所有人共享您的请求池,这是您没有解决的问题。
-
是的,你是对的。 cors-anywhere github 确实提到我使用的 URL 仅用于演示目的。我已经在 Heroku 上托管了我自己的实例,并将继续测试。
标签: javascript reactjs throttling rate-limiting