GenerateAnalysisPdfJob.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Jobs;
  3. use App\Services\ExamPdfExportService;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Support\Facades\Log;
  10. use Throwable;
  11. class GenerateAnalysisPdfJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. public string $paperId;
  15. public string $studentId;
  16. public ?string $recordId;
  17. public int $tries = 3;
  18. public int $timeout = 300;
  19. public array $backoff = [5, 10, 20];
  20. public function __construct(string $paperId, string $studentId, ?string $recordId = null)
  21. {
  22. $this->paperId = $paperId;
  23. $this->studentId = $studentId;
  24. $this->recordId = $recordId;
  25. // 指定使用 pdf 队列,由独立的 pdf-worker 容器处理
  26. $this->onQueue('pdf');
  27. // 避免事务未提交时 worker 提前消费导致读到未提交数据
  28. $this->afterCommit();
  29. }
  30. public function handle(ExamPdfExportService $pdfExportService): void
  31. {
  32. try {
  33. Log::info('开始处理学情分析PDF生成队列任务', [
  34. 'paper_id' => $this->paperId,
  35. 'student_id' => $this->studentId,
  36. 'record_id' => $this->recordId,
  37. 'attempt' => $this->attempts(),
  38. ]);
  39. // 生成学情分析PDF
  40. $pdfUrl = $pdfExportService->generateAnalysisReportPdf(
  41. $this->paperId,
  42. $this->studentId,
  43. $this->recordId
  44. );
  45. if (! $pdfUrl) {
  46. throw new \RuntimeException('学情分析PDF生成失败:返回空URL');
  47. }
  48. Log::info('学情分析PDF生成成功', [
  49. 'paper_id' => $this->paperId,
  50. 'student_id' => $this->studentId,
  51. 'record_id' => $this->recordId,
  52. 'pdf_url' => $pdfUrl,
  53. ]);
  54. } catch (\Throwable $e) {
  55. Log::error('学情分析PDF生成队列任务失败', [
  56. 'paper_id' => $this->paperId,
  57. 'student_id' => $this->studentId,
  58. 'record_id' => $this->recordId,
  59. 'error' => $e->getMessage(),
  60. 'trace' => $e->getTraceAsString(),
  61. 'attempt' => $this->attempts(),
  62. ]);
  63. throw $e;
  64. }
  65. }
  66. public function failed(Throwable $exception): void
  67. {
  68. Log::error('学情分析PDF生成队列任务最终失败', [
  69. 'paper_id' => $this->paperId,
  70. 'student_id' => $this->studentId,
  71. 'record_id' => $this->recordId,
  72. 'error' => $exception->getMessage(),
  73. ]);
  74. }
  75. }