我的代码:
const limit = require('simple-rate-limiter')
const request = limit(require('request').defaults({
gzip: true
})).to(15).per(10 * 1000) // 15 requests per 10 seconds
request(API_ENDPOINT, callback) // call API thousands of times
图书馆:simple-rate-limiter以及众所周知的request图书馆。
<小时/>我需要调用第 3 方 API 数千次,而该 API 每 10 秒只允许 15 个请求。上面的代码没有正确限制我的请求,因此服务器发送 429 Too Many Requests
HTTP 状态代码。
我可以一次发送 15 个请求,但程序必须等待 10 秒才能发送更多请求,否则会再次收到 429
响应。
我认为这是因为与服务器的连接需要数百毫秒到几秒的时间(300ms-2s
)。所以我的请求时间和服务器收到请求的时间不一样。
来自服务器的响应包含一个Date
header 。可以以某种方式使用它来正确限制请求吗?有没有一个图书馆可以让这变得容易?即使在实现正确的速率限制后,如果您收到 429
响应,是否也有一种简单的方法可以重试?
最佳答案
好的,所以方法是检查从通话开始到结束已经过去了多少时间。我假设每 667 毫秒调用一次 API 是安全的。
var startTime,
endTime;
function timeDiff() {
return (endTime.getTime() - startTime.getTime());
}
function startRequest() {
startTime = new Date();
request(API_ENDPOINT, requestCallback)
}
function requestCallback(data) {
//do what you please with data
endTime = new Date();
var diff = timeDiff();
if(diff < 667) {
//To early to start API, need to wait.
setTimeout(startRequest, 667 - diff);
} else {
//It is fine to start request now.
setTimeout(startRequest);
}
}
startRequest();
此代码将在调用完成后立即继续调用 API,除非它完成的速度快于 667 毫秒。
关于javascript - 对第 3 方 API 的请求进行速率限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481875/