在宜搭中调用第三方接口时经常需要控制请求的QPS,所以写了一个控制类,方便使用
class QPSControl {
constructor(qps, fillRate = 0) {
this.qps = qps;
this.fillRate = fillRate || qps;
this.tokens = qps;
this.lastFillTime = Date.now();
}
wait() {
return new Promise(resolve => {
const tryTake = () => {
this.fill();
if (this.tokens < 1) {
setTimeout(tryTake, 1000 / this.fillRate);
} else {
this.tokens -= 1;
resolve();
}
};
tryTake();
});
}
fill() {
const now = Date.now();
const deltaTime = now - this.lastFillTime;
const filledTokens = deltaTime * this.fillRate / 1000;
this.tokens = Math.min(this.qps, this.tokens + filledTokens);
this.lastFillTime = now;
}
}
export function didMount() {
// 创建一个新的QPSControl实例,容量为10,填充率为10(每秒10个令牌)
// 钉钉开放平台的QPS限制为20,如果用户多了有可能出现多用户同时请求的情况,所以不要设置太大
const qpsController = new QPSControl(10, 10);
this.setState({ qpsController })
}
在发送请求前先获取Token
await this.state.qpsController.wait()
response = await this.dataSourceMap.xxx.load(params)
console.log(response)
使用then回调示例
this.state.qpsController.take().then(()=>{
this.dataSourceMap.xxx.load(params)
.then(response=>{
console.log(response)
})
})
发表评论 取消回复