| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace App\Module\Ulogic\Queues;
- use App\Module\Ulogic\Models\AppMessage;
- use App\Module\Ulogic\Services\AppMessageService;
- use UCore\Queue\QueueJob;
- use Illuminate\Support\Facades\Log;
- /**
- * 应用消息发送队列任务类
- *
- * 该类负责异步处理消息的发送,支持失败重试和超时控制
- * 使用Laravel的队列系统实现异步发送,避免阻塞主流程
- */
- class SendAppMessageQueue extends QueueJob
- {
- /**
- * 待发送的消息实例
- *
- * @var AppMessage
- */
- protected AppMessage $message;
- /**
- * 最大重试次数
- *
- * 当任务执行失败时,系统会自动重试,最多重试3次
- *
- * @var int
- */
- public $tries = 3;
- /**
- * 任务超时时间(秒)
- *
- * 如果任务执行超过60秒仍未完成,系统会认为任务超时并终止执行
- *
- * @var int
- */
- public $timeout = 60;
- /**
- * 创建队列任务实例
- *
- * @param AppMessage $message 需要发送的消息实例
- */
- public function __construct(AppMessage $message)
- {
- $this->message = $message;
- parent::__construct(['message_id' => $message->id]);
- }
- /**
- * 执行队列任务
- *
- * @return bool
- */
- public function run(): bool
- {
- try {
- // 获取消息服务实例
- $messageService = app(AppMessageService::class);
- // 处理消息发送逻辑
- // TODO: 实现消息发送逻辑
- // 例如:发送WebSocket通知、更新消息状态等
- return true;
- } catch (\Exception $e) {
- // 记录错误日志
- Log::error('发送应用消息失败', [
- 'message_id' => $this->message->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * 获取任务数据
- *
- * @return array
- */
- public function payload()
- {
- return [
- 'message_id' => $this->message->id,
- 'message_data' => $this->message->toArray()
- ];
- }
- /**
- * 处理失败的任务
- *
- * 当任务执行失败或发生异常时会调用此方法
- * 可以在这里实现:
- * 1. 记录错误日志
- * 2. 发送失败通知
- * 3. 更新消息状态为发送失败
- * 4. 触发告警
- * 等失败处理逻辑
- *
- * @param \Throwable $exception 导致任务失败的异常实例
- * @return void
- */
- public function failed(\Throwable $exception): void
- {
- // TODO: 实现失败处理逻辑
- // 例如:记录失败日志、更新消息状态等
- }
- }
|