1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
無法使用任何內(nèi)置功能來限制 PHP 函數(shù)的速率。您可以編寫一些簡(jiǎn)單的包裝器,它每分鐘僅調(diào)用 API 給定的次數(shù)。一個(gè)粗略的示例如下所示:
function callAPI($api) {
static $lastRequest;
$maxRequestsPerMin = 20;
if (isset($lastRequest)) {
$delay = 60 / $maxRequestsPerMin; // 60 seconds / $maxRequestsPerMin
if ((microtime(true) - $lastRequest) < $delay) {
// Sleep until the delay is reached
$sleepAmount = ($delay - microtime(true) + $lastRequest) * (1000 ** 2);
usleep($sleepAmount);
}
}
$lastRequest = microtime(true);
// Call you API here
}
但是,這只會(huì)限制此特定腳本的速率。如果您執(zhí)行另一個(gè),那么您將啟動(dòng)另一個(gè)計(jì)數(shù)器?;蛘?,您可以將一些循環(huán)表存儲(chǔ)在平面文件或數(shù)據(jù)庫(kù)中,并在每次要調(diào)用 API 時(shí)對(duì)其進(jìn)行檢查。
對(duì)于高級(jí)用法,您應(yīng)該查看消息隊(duì)列或 ReactPHP。如果此類功能會(huì)暴露給最終用戶,您不希望掛起您的服務(wù)器。
- 1 回答
- 0 關(guān)注
- 139 瀏覽
添加回答
舉報(bào)