Laravel 命令超时优化:批量插入与状态预更新实战指南

12次阅读

Laravel 命令超时优化:批量插入与状态预更新实战指南

本文针对 laravel artisan 命令因处理海量数据(如 800 万条 `incomes` 记录)导致超时的问题,提供基于批量插入(`income::insert()`)、预批量状态更新、懒加载优化的完整解决方案。

laravel 8.x 环境中执行类似 php artisan command:here 的长周期命令时,若涉及对数十万订阅(subscriptions)及数百万收入记录(incomes)的逐条判断与写入,极易触发 PHP 执行超时(默认 30 秒)或 Forge/Nginx 层级超时(常见为 60–300 秒),最终返回 “Timed Out”。根本原因在于原逻辑中大量使用 new Income()->save() 触发 N 次独立数据库 INSERT 查询(N = 总需补录条数),同时频繁调用模型关系与单条更新,I/O 和 ORM 开销极高。

核心优化策略有三:

  1. 批量状态预更新:在循环前,直接通过 sql 更新所有已满 200 条 income 的 ACTIVE 订阅为 COMPLETED,避免进入低效循环;
  2. 批量插入替代逐条保存:将 $max 条待插入记录构造成二维数组,一次性调用 Income::insert(),将 N 次查询压缩为 1 次;
  3. 懒加载 + 预加载精简:继续使用 ->lazy() 防止内存溢出,但移除冗余的 withCount(‘income’)(因其在批量更新后已不可靠),改用 has(‘income’, ‘

以下是优化后的完整命令实现:

namespace AppConsoleCommands;  use AppModelsIncome; use AppModelsSubscription; use IlluminateConsoleCommand; use IlluminateSupportFacadesLog;  class SomeCommand extends Command {     protected $signature = 'command:here';      public function handle()     {         // ✅ 关键:全局预更新——跳过所有已满 200 条 income 的 ACTIVE 订阅         Subscription::where('status', 'ACTIVE')             ->has('incomes', '>=', 200)             ->update(['status' => 'COMPLETED']);          // ✅ 使用 lazy() 分块处理,避免内存爆炸;仅预加载 latestIncome(非全部 incomes)         foreach (Subscription::with('latestIncome')             ->where('status', 'ACTIVE')             ->lazy(500) as $subscription) { // 每次加载 500 条,可按需调整              $recent_bonus = $subscription->latestIncome;              if (!$recent_bonus) {                 continue; // 无最新 income,暂不处理(或按业务补充逻辑)             }              $hour_difference = now()->diffInHours($recent_bonus->created_at);              if ($hour_difference <= 1) {                 continue; // 不足 1 小时,跳过             }              // 查询当前 income 数量(避免 withCount 在大数据量下拖慢查询)             $count_earnings = $subscription->incomes()->count();              if ($count_earnings >= 200) {                 $subscription->update(['status' => 'COMPLETED']);                 continue;             }              $to_insert = 200 - $count_earnings;             $max = min($hour_difference, $to_insert); // 取更小值              if ($max > 0) {                 // ✅ 批量插入:生成 $max 条相同结构数据(可扩展为动态金额逻辑)                 $records = collect()->pad($max, [                     'user_id' => $subscription->user_id,                     'subscription_id' => $subscription->id,                     'amount' => round(100 * 0.002 * 100), // = 20,建议提取为常量或配置                     'created_at' => now(),                     'updated_at' => now(),                 ])->all();                  Income::insert($records);                  Log::info("Fixed subscription {$subscription->id} | User {$subscription->user_id} | Inserted {$max} incomes");             }              // ✅ 循环后检查是否达上限,统一更新状态(避免每条都 update)             if ($count_earnings + $max >= 200) {                 $subscription->update(['status' => 'COMPLETED']);             }         }          // ✅ 最终兜底:确保所有达标的订阅状态准确(补偿并发/异常场景)         Subscription::where('status', 'ACTIVE')             ->has('incomes', '>=', 200)             ->update(['status' => 'COMPLETED']);     } }

关键注意事项:

  • ? 时间限制仍需显式设置:ini_set(‘max_execution_time’, 0) 仅对 CLI 有效,但建议配合 set_time_limit(0) 更稳妥,并确认 Forge 服务器的 pm.max_execution_time(php-FPM)或 fastcgi_read_timeout(nginx)未施加额外限制;
  • ? 事务与错误恢复:生产环境建议包裹 DB::transaction() 并捕获异常,对失败批次记录日志并支持断点续跑(例如记录最后处理的 subscription_id);
  • ? 索引验证:确保 incomes.subscription_id、incomes.created_at 及 subscriptions.status 字段均有高效索引,否则 has() 和 latestOfMany() 查询将严重退化;
  • ? 内存监控:lazy(500) 是平衡速度与内存的关键,可结合 memory_get_usage() 日志观察,必要时降至 200 或启用 cursorPaginate()(Laravel 9+)进一步降低内存占用

通过以上重构,原需数小时的命令可压缩至数分钟内完成,且稳定性显著提升——这才是面向千万级数据的 Laravel 命令最佳实践。

text=ZqhQzanResources