| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Module\Notification\Queues;
- use App\Module\Notification\Models\NotificationLog;
- use App\Module\Notification\Services\NotificationService;
- use UCore\Queue\QueueJob;
- use Illuminate\Support\Facades\Log;
- /**
- * 发送通知队列任务类
- *
- * 该类负责异步处理通知的发送,支持失败重试和超时控制
- */
- class SendNotificationQueue extends QueueJob
- {
- protected NotificationLog $notification;
- /**
- * 最大重试次数
- *
- * @var int
- */
- public $tries = 3;
- /**
- * 超时时间
- *
- * @var int
- */
- public $timeout = 60;
- /**
- * 创建队列任务
- *
- * @param NotificationLog $notification
- */
- public function __construct(NotificationLog $notification)
- {
- $this->notification = $notification;
- parent::__construct(['notification_id' => $notification->id]);
- }
- /**
- * 执行队列任务
- *
- * @return bool
- */
- public function run(): bool
- {
- try {
- // 获取通知服务实例
- $notificationService = app(NotificationService::class);
- // 处理通知发送
- $notificationService->handleNotification($this->notification);
- return true;
- } catch (\Exception $e) {
- // 记录错误日志
- Log::error('发送通知失败', [
- 'notification_id' => $this->notification->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 获取任务数据
- *
- * @return array
- */
- public function payload()
- {
- return [
- 'notification_id' => $this->notification->id,
- 'notification_data' => $this->notification->toArray()
- ];
- }
- /**
- * 处理失败的任务
- *
- * @param \Throwable $exception
- * @return void
- */
- public function failed(\Throwable $exception): void
- {
- $this->notification->update([
- 'status' => 'FAILED',
- 'message' => $exception->getMessage()
- ]);
- }
- }
|