SendNotificationQueue.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Module\Notification\Queues;
  3. use App\Module\Notification\Models\NotificationLog;
  4. use App\Module\Notification\Services\NotificationService;
  5. use UCore\Queue\QueueJob;
  6. use Illuminate\Support\Facades\Log;
  7. /**
  8. * 发送通知队列任务类
  9. *
  10. * 该类负责异步处理通知的发送,支持失败重试和超时控制
  11. */
  12. class SendNotificationQueue extends QueueJob
  13. {
  14. protected NotificationLog $notification;
  15. /**
  16. * 最大重试次数
  17. *
  18. * @var int
  19. */
  20. public $tries = 3;
  21. /**
  22. * 超时时间
  23. *
  24. * @var int
  25. */
  26. public $timeout = 60;
  27. /**
  28. * 创建队列任务
  29. *
  30. * @param NotificationLog $notification
  31. */
  32. public function __construct(NotificationLog $notification)
  33. {
  34. $this->notification = $notification;
  35. parent::__construct(['notification_id' => $notification->id]);
  36. }
  37. /**
  38. * 执行队列任务
  39. *
  40. * @return bool
  41. */
  42. public function run(): bool
  43. {
  44. try {
  45. // 获取通知服务实例
  46. $notificationService = app(NotificationService::class);
  47. // 处理通知发送
  48. $notificationService->handleNotification($this->notification);
  49. return true;
  50. } catch (\Exception $e) {
  51. // 记录错误日志
  52. Log::error('发送通知失败', [
  53. 'notification_id' => $this->notification->id,
  54. 'error' => $e->getMessage(),
  55. 'trace' => $e->getTraceAsString()
  56. ]);
  57. return false;
  58. }
  59. }
  60. /**
  61. * 获取任务数据
  62. *
  63. * @return array
  64. */
  65. public function payload()
  66. {
  67. return [
  68. 'notification_id' => $this->notification->id,
  69. 'notification_data' => $this->notification->toArray()
  70. ];
  71. }
  72. /**
  73. * 处理失败的任务
  74. *
  75. * @param \Throwable $exception
  76. * @return void
  77. */
  78. public function failed(\Throwable $exception): void
  79. {
  80. $this->notification->update([
  81. 'status' => 'FAILED',
  82. 'message' => $exception->getMessage()
  83. ]);
  84. }
  85. }