RabbitMQWorker.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use App\Jobs\ProcessAITranslateJob;
  6. use App\Jobs\BaseRabbitMQJob;
  7. use Illuminate\Support\Facades\Log;
  8. use PhpAmqpLib\Exception\AMQPTimeoutException;
  9. use PhpAmqpLib\Wire\AMQPTable;
  10. use App\Services\RabbitMQService;
  11. use App\Exceptions\SectionTimeoutException;
  12. class RabbitMQWorker extends Command
  13. {
  14. /**
  15. * The name and signature of the console command.
  16. * php -d memory_limit=128M artisan rabbitmq:consume ai_translate
  17. * @var string
  18. */
  19. protected $signature = 'rabbitmq:consume {queue} {--reset-loop-count}';
  20. protected $description = '消费 RabbitMQ 队列消息';
  21. private $connection;
  22. private $channel;
  23. private $processedCount = 0;
  24. private $maxLoopCount = 0;
  25. private $queueName;
  26. private $queueConfig;
  27. private $shouldStop = false;
  28. private $timeout = 15;
  29. private $job = null;
  30. public function handle()
  31. {
  32. if (\App\Tools\Tools::isStop()) {
  33. return 0;
  34. }
  35. $this->queueName = $this->argument('queue');
  36. $this->queueConfig = config("mint.rabbitmq.queues.{$this->queueName}");
  37. if (!$this->queueConfig) {
  38. $this->error("队列 {$this->queueName} 的配置不存在");
  39. return 1;
  40. }
  41. $this->maxLoopCount = $this->queueConfig['max_loop_count'];
  42. $this->info("启动 RabbitMQ Worker");
  43. $this->info("队列: {$this->queueName}");
  44. $this->info("最大循环次数: {$this->maxLoopCount}");
  45. $this->info("重试次数: {$this->queueConfig['retry_times']}");
  46. $consume = app(RabbitMQService::class);
  47. try {
  48. $consume->setupQueue($this->queueName);
  49. $this->channel = $consume->getChannel();
  50. $this->startConsuming();
  51. } catch (\Exception $e) {
  52. $this->error("Worker 启动失败: " . $e->getMessage());
  53. Log::error("RabbitMQ Worker 启动失败", [
  54. 'queue' => $this->queueName,
  55. 'error' => $e->getMessage()
  56. ]);
  57. return 1;
  58. } finally {
  59. $this->cleanup();
  60. }
  61. return 0;
  62. }
  63. private function startConsuming()
  64. {
  65. $callback = function (AMQPMessage $msg) {
  66. $this->processMessage($msg);
  67. };
  68. $this->channel->basic_consume(
  69. $this->queueName,
  70. '', // consumer_tag
  71. false, // no_local
  72. false, // no_ack
  73. false, // exclusive
  74. false, // nowait
  75. $callback
  76. );
  77. $this->info("开始消费消息... 按 Ctrl+C 退出");
  78. // 设置信号处理
  79. if (extension_loaded('pcntl')) {
  80. pcntl_signal(SIGTERM, [$this, 'handleSignal']);
  81. pcntl_signal(SIGINT, [$this, 'handleSignal']);
  82. }
  83. while ($this->channel->is_consuming() && !$this->shouldStop) {
  84. try {
  85. $this->channel->wait(null, false, $this->timeout);
  86. } catch (AMQPTimeoutException $e) {
  87. //忽略
  88. } catch (\Exception $e) {
  89. $this->error($e->getMessage());
  90. throw $e;
  91. }
  92. if (extension_loaded('pcntl')) {
  93. pcntl_signal_dispatch();
  94. }
  95. // 检查是否达到最大循环次数
  96. if ($this->processedCount >= $this->maxLoopCount) {
  97. $this->info("达到最大循环次数 ({$this->maxLoopCount}),Worker 自动退出");
  98. break;
  99. }
  100. if (\App\Tools\Tools::isStop()) {
  101. //检测到停止标记
  102. break;
  103. }
  104. }
  105. }
  106. private function processMessage(AMQPMessage $msg)
  107. {
  108. try {
  109. Log::info('processMessage start', ['message_id' => $msg->get('message_id')]);
  110. $data = json_decode($msg->getBody());
  111. $this->info("processMessage start " . $msg->get('message_id') . '[' . count($data) . ']');
  112. if (json_last_error() !== JSON_ERROR_NONE) {
  113. throw new \Exception("JSON 解析失败: " . json_last_error_msg());
  114. }
  115. // 获取重试次数(从消息头中获取)
  116. $retryCount = 0;
  117. if ($msg->has('application_headers')) {
  118. $headers = $msg->get('application_headers')->getNativeData();
  119. $retryCount = $headers['retry_count'] ?? 0;
  120. }
  121. // 根据队列类型创建对应的 Job
  122. $this->job = $this->createJob($msg->get('message_id'), $data, $retryCount);
  123. try {
  124. // 执行业务逻辑
  125. $successful = $this->job->handle();
  126. if ($successful) {
  127. // 成功处理,确认消息
  128. $msg->ack();
  129. }
  130. $this->processedCount++;
  131. $this->info("消息处理成功 [{$this->processedCount}/{$this->maxLoopCount}]");
  132. } catch (SectionTimeoutException $e) {
  133. $msg->nack(true, false);
  134. Log::warning('attempt to requeue the message message_id:' . $msg->get('message_id'));
  135. } catch (\Exception $e) {
  136. $this->handleJobException($msg, $data, $retryCount, $e);
  137. }
  138. } catch (\Exception $e) {
  139. $this->error("消息处理异常: " . $e->getMessage());
  140. Log::error("RabbitMQ 消息处理异常", [
  141. 'queue' => $this->queueName,
  142. 'error' => $e->getMessage(),
  143. 'message_body' => $msg->getBody()
  144. ]);
  145. // 拒绝消息并发送到死信队列
  146. //$msg->nack(false, false);
  147. $this->sendToDeadLetterQueue($data, $e);
  148. $msg->ack(); // 确认原消息以避免重复
  149. $this->error("已发送到死信队列");
  150. $this->processedCount++;
  151. }
  152. }
  153. private function createJob(string $messageId, array $data, int $retryCount): BaseRabbitMQJob
  154. {
  155. // 根据队列名称创建对应的 Job 实例
  156. switch ($this->queueName) {
  157. case 'ai_translate':
  158. return new ProcessAITranslateJob(
  159. $this->queueName,
  160. $messageId,
  161. $data,
  162. $retryCount,
  163. );
  164. // 可以添加更多队列类型
  165. default:
  166. throw new \Exception("未知的队列类型: {$this->queueName}");
  167. }
  168. }
  169. private function handleJobException(AMQPMessage $msg, array $data, int $retryCount, \Exception $e)
  170. {
  171. $maxRetries = $this->queueConfig['retry_times'];
  172. if ($retryCount < $maxRetries - 1) {
  173. // 还有重试机会,重新入队
  174. $this->requeueMessage($msg, $data, $retryCount + 1);
  175. $this->info("消息重新入队,重试次数: " . ($retryCount + 1) . "/{$maxRetries}");
  176. } else {
  177. // 超过重试次数,发送到死信队列
  178. $this->sendToDeadLetterQueue($data, $e);
  179. $msg->ack(); // 确认原消息以避免重复
  180. $this->error("消息超过最大重试次数,已发送到死信队列 ");
  181. Log::error("消息超过最大重试次数,已发送到死信队列 message_id=" . $msg->get('message_id'));
  182. }
  183. $this->processedCount++;
  184. }
  185. private function requeueMessage(AMQPMessage $msg, array $data, int $newRetryCount)
  186. {
  187. // 添加重试计数到消息头
  188. // 使用 AMQPTable 包装头部数据
  189. $headers = new AMQPTable([
  190. 'retry_count' => $newRetryCount,
  191. 'original_queue' => $this->queueName,
  192. 'retry_timestamp' => time()
  193. ]);
  194. $newMsg = new AMQPMessage(
  195. json_encode($data, JSON_UNESCAPED_UNICODE),
  196. [
  197. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  198. 'timestamp' => time(),
  199. 'message_id' => $msg->get('message_id'),
  200. 'application_headers' => $headers,
  201. "content_type" => 'application/json; charset=utf-8'
  202. ]
  203. );
  204. // 发布到同一队列
  205. $this->channel->basic_publish($newMsg, '', $this->queueName);
  206. // 确认原消息
  207. $msg->ack();
  208. }
  209. private function sendToDeadLetterQueue(array $data, \Exception $e)
  210. {
  211. $dlqName = $this->queueConfig['dead_letter_queue'];
  212. $dlqData = [
  213. 'original_message' => $data,
  214. 'failure_reason' => $e->getMessage(),
  215. 'failed_at' => date('Y-m-d H:i:s'),
  216. 'queue' => $this->queueName,
  217. 'max_retries' => $this->queueConfig['retry_times']
  218. ];
  219. $dlqMsg = new AMQPMessage(
  220. json_encode($dlqData),
  221. ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]
  222. );
  223. $this->channel->basic_publish($dlqMsg, '', $dlqName);
  224. Log::error("消息发送到死信队列", [
  225. 'original_queue' => $this->queueName,
  226. 'dead_letter_queue' => $dlqName,
  227. 'error' => $e->getMessage()
  228. ]);
  229. }
  230. public function handleSignal($signal)
  231. {
  232. $this->info("接收到退出信号,正在优雅关闭...");
  233. $this->shouldStop = true;
  234. if ($this->job) {
  235. $this->job->stop();
  236. }
  237. if ($this->channel && $this->channel->is_consuming()) {
  238. //$this->channel->basic_cancel_on_shutdown(true);
  239. $this->channel->basic_cancel('');
  240. }
  241. }
  242. private function cleanup()
  243. {
  244. try {
  245. if ($this->channel) {
  246. $this->channel->close();
  247. }
  248. if ($this->connection) {
  249. $this->connection->close();
  250. }
  251. $this->info("连接已关闭,处理了 {$this->processedCount} 条消息");
  252. } catch (\Exception $e) {
  253. $this->error("清理资源时出错: " . $e->getMessage());
  254. }
  255. }
  256. }