| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- namespace App\Console\Commands;
- use App\Services\DeepSeek\DeepSeekService;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- /**
- * 剧本资产生成异步任务 worker
- *
- * 由 text:generate:dispatch 拉起;通过 MySQL 命名锁防止同一任务被重复执行。
- */
- class TextScriptGenerateRunCommand extends Command
- {
- /**
- * 任务处理锁前缀(配合 MySQL GET_LOCK 使用)
- */
- public const LOCK_PREFIX = 'script_text_generate_';
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'text:generate:run {task_id : 剧本资产生成任务ID}';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = '剧本资产生成worker:执行指定任务的流式模型生成并落库';
- /**
- * @var DeepSeekService
- */
- protected $deepSeekService;
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct(DeepSeekService $deepSeekService)
- {
- parent::__construct();
- $this->deepSeekService = $deepSeekService;
- }
- /**
- * Execute the console command.
- *
- * @return int
- */
- public function handle()
- {
- set_time_limit(0);
- $taskId = (int)$this->argument('task_id');
- $lockName = self::LOCK_PREFIX . $taskId;
- // 非阻塞抢占该任务的处理锁;抢不到说明已有其他进程正在处理
- $acquired = DB::selectOne('SELECT GET_LOCK(?, 0) AS acquired', [$lockName]);
- if (!$acquired || (int)$acquired->acquired !== 1) {
- dLog('command')->info("task_id: {$taskId} 正在被其他进程处理,本次直接退出");
- return 0;
- }
- dLog('command')->info("task_id: {$taskId} 抢占处理锁成功,开始处理...");
- try {
- $result = $this->deepSeekService->runScriptGenerateTaskAsync($taskId);
- dLog('command')->info('task_id: ' . $taskId . ' 处理结果: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
- if (empty($result['ok'])) {
- logDB('command', 'error', '剧本资产生成worker异常', [
- 'task_id' => $taskId,
- 'status' => $result['status'] ?? null,
- 'error' => $result['error'] ?? '未知错误',
- ]);
- }
- } catch (\Throwable $e) {
- dLog('command')->error("task_id: {$taskId} 处理异常: " . $e->getMessage());
- logDB('command', 'error', '剧本资产生成worker异常', [
- 'task_id' => $taskId,
- 'error' => $e->getMessage(),
- ]);
- } finally {
- // 显式释放处理锁;即使进程异常退出,连接断开后 MySQL 也会自动释放
- DB::statement('SELECT RELEASE_LOCK(?)', [$lockName]);
- dLog('command')->info("task_id: {$taskId} 处理结束,已释放处理锁");
- }
- return 0;
- }
- }
|