import { Mutex } from 'async-mutex';
// 创建互斥锁
private mutex = new Mutex();
// 共享的 Number 变量
private sharedNumber = 0;
/**
* 调用淘系api
* @param {TopApiParam} data api名和入参等
*/
topApi = (data: TopApiParam, nick?:string): Promise<any> => {
return new Promise(async (resolve, reject) => {
// 单机qps150限制
// 等待获取锁
const release = await this.mutex.acquire();
try {
// 在锁的保护下操作共享的 Number 变量
if(this.sharedNumber >= 100){
// if(this.sharedNumber >= 75){
// sleep 1.5s
await sleep(1500);
this.sharedNumber = 0;
}
this.sharedNumber += 1;
this.logger.info(`当前锁数量: ${this.sharedNumber}`)
await sleep(10)
}catch (e) {
this.logger.error(`【淘宝API调用异常】锁获取异常: ${e.message} `)
} finally {
// 释放锁
release();
}
const product = !isEmpty(data.product) ? data.product : 'item';
const options: any = {
appkey: process.env[`top.${product}.appkey`],
appsecret: process.env[`top.${product}.appsign`],
url: TAO_API_GATWAY_URL,
};
// isNotNeedSessionId, 默认增加,有特殊参数时,不增加
if (isEmpty(data.isNotNeedSessionId)) {
data.params['session'] = await this.baseService.getAccessToken(PRODUCT_ITEM, PLATFORM_TAOBAO, nick).catch((e) => {
reject(e);
});
}
const client = new ApiClient(options);
client.execute(data.apiName, data.params, (error, response) => {
if (!error) {
resolve(response);
} else {
console.log('淘宝api', error);
this.logger.error(`【淘宝API调用异常】: ${error.message} `)
resolve(error);
}
});
}).catch((e) => {
this.logger.error(`【淘宝API调用异常】: ${e.message} `)
throw new CustomException({ message: `淘宝API调用异常${e.message}`, code: 500 });
});
};