Com*_*cus 2 php throttling task-queue redis laravel
我正在使用 Laravel Horizon 和 Redis,我正在尝试限制它。我使用的外部 API 的速率限制为每分钟 100 个请求。我需要提出大约 700 个请求。我进行了设置,以便添加到队列中的每个作业仅在作业本身中执行一个 API 调用。因此,如果我限制队列,我应该能够保持在限制范围内。由于某种原因,没有发生限制,而是超出了队列(当然,这会触发许多 API 错误)。然而,节流阀在本地工作,但不在我的服务器上工作。
我最初试图根据 Laravel 的队列文档进行限制,但只能让它在本地工作,所以我转而尝试Github 上的laravel-queue-rate-limit包。根据自述文件,我将以下内容添加到我的queue.php配置文件中:
'rateLimits' => [
'default' => [ // queue name
'allows' => 75, // 75 job
'every' => 60 // per 60 seconds
]
],
Run Code Online (Sandbox Code Playgroud)
由于某种原因,当我在本地 Ubuntu 环境中运行它时,限制可以正常工作,但它在我的服务器(也是 Ubuntu)上不起作用。在服务器上,它只是吹过队列,就好像没有适当的节流一样。
我是否做错了什么,或者可能有更好的方法来处理速率受限的外部 API?
编辑1:
配置/horizon.php
'environments' => [
'production' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'processes' => 3,
'tries' => 100,
],
],
Run Code Online (Sandbox Code Playgroud)
启动大多数作业的句柄之一:
public function handle()
{
$updatedPlayerIds = [];
foreach ($this->players as $player) {
$playerUpdate = Player::updateOrCreate(
[
'id' => $player['id'],
],
[
'faction_id' => $player['faction_id'],
'name' => $player['name'],
]
);
// Storing id's of records updated
$updatedPlayerIds[] = $playerUpdate->id;
// If it's a new player or the player was last updated awhile ago, then get new data!
if ($playerUpdate->wasRecentlyCreated ||
$playerUpdate->last_complete_update_at == null ||
Carbon::parse($playerUpdate->last_complete_update_at)->diffInHours(Carbon::now()) >= 6) {
Log::info("Updating '{$playerUpdate->name}' with new data", ['playerUpdate' => $playerUpdate]);
UpdatePlayer::dispatch($playerUpdate);
} else {
// Log::debug("Player data fresh, no update performed", ['playerUpdate' => $playerUpdate]);
}
}
//Delete any ID's that were not updated via the API
Player::where('faction_id', $this->faction->id)->whereNotIn('id', $updatedPlayerIds)->delete();
}
Run Code Online (Sandbox Code Playgroud)
另外,这是我制作的一个粗略图表,试图说明我如何在短时间内生成多个作业 PHP 文件,尤其是像这样updatePlayer()经常生成 700 次的文件。
看来您提到的软件包(laravel-queue-rate-limit)与 Horizon不能很好地配合。使用 Laravel 的内置方法可能会更好。
在 Laravel 的队列中,添加->block(60)匹配->every(60),以便默认超时不会启动并在 60 秒之前调用另一个回调。
Redis::throttle('torn-api')->allow(75)->every(60)->block(60)
Run Code Online (Sandbox Code Playgroud)
另外,请考虑向 Horizon 的 config 添加超时和最大重试值(config/horizon.php)。failed您还可以使用作业本身中的方法记录任何异常。看到这个。
Horizon 配置中的设置retry_after和值。timeout您retry_after在配置中的价值应始终大于完成工作所需的时间。并且该timeout值应该比该值短几秒retry_after。“这将确保处理给定作业的工作人员始终在重试作业之前被杀死。” 请参阅文档中的此问题和这一点。