SendAppMessageQueue.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace App\Module\Ulogic\Queues;
  3. use App\Module\Ulogic\Models\AppMessage;
  4. use App\Module\Ulogic\Services\AppMessageService;
  5. use UCore\Queue\QueueJob;
  6. use Illuminate\Support\Facades\Log;
  7. /**
  8. * 应用消息发送队列任务类
  9. *
  10. * 该类负责异步处理消息的发送,支持失败重试和超时控制
  11. * 使用Laravel的队列系统实现异步发送,避免阻塞主流程
  12. */
  13. class SendAppMessageQueue extends QueueJob
  14. {
  15. /**
  16. * 待发送的消息实例
  17. *
  18. * @var AppMessage
  19. */
  20. protected AppMessage $message;
  21. /**
  22. * 最大重试次数
  23. *
  24. * 当任务执行失败时,系统会自动重试,最多重试3次
  25. *
  26. * @var int
  27. */
  28. public $tries = 3;
  29. /**
  30. * 任务超时时间(秒)
  31. *
  32. * 如果任务执行超过60秒仍未完成,系统会认为任务超时并终止执行
  33. *
  34. * @var int
  35. */
  36. public $timeout = 60;
  37. /**
  38. * 创建队列任务实例
  39. *
  40. * @param AppMessage $message 需要发送的消息实例
  41. */
  42. public function __construct(AppMessage $message)
  43. {
  44. $this->message = $message;
  45. parent::__construct(['message_id' => $message->id]);
  46. }
  47. /**
  48. * 执行队列任务
  49. *
  50. * @return bool
  51. */
  52. public function run(): bool
  53. {
  54. try {
  55. // 获取消息服务实例
  56. $messageService = app(AppMessageService::class);
  57. // 处理消息发送逻辑
  58. // TODO: 实现消息发送逻辑
  59. // 例如:发送WebSocket通知、更新消息状态等
  60. return true;
  61. } catch (\Exception $e) {
  62. // 记录错误日志
  63. Log::error('发送应用消息失败', [
  64. 'message_id' => $this->message->id,
  65. 'error' => $e->getMessage(),
  66. 'trace' => $e->getTraceAsString()
  67. ]);
  68. return false;
  69. }
  70. }
  71. /**
  72. * 获取任务数据
  73. *
  74. * @return array
  75. */
  76. public function payload()
  77. {
  78. return [
  79. 'message_id' => $this->message->id,
  80. 'message_data' => $this->message->toArray()
  81. ];
  82. }
  83. /**
  84. * 处理失败的任务
  85. *
  86. * 当任务执行失败或发生异常时会调用此方法
  87. * 可以在这里实现:
  88. * 1. 记录错误日志
  89. * 2. 发送失败通知
  90. * 3. 更新消息状态为发送失败
  91. * 4. 触发告警
  92. * 等失败处理逻辑
  93. *
  94. * @param \Throwable $exception 导致任务失败的异常实例
  95. * @return void
  96. */
  97. public function failed(\Throwable $exception): void
  98. {
  99. // TODO: 实现失败处理逻辑
  100. // 例如:记录失败日志、更新消息状态等
  101. }
  102. }