RabbitMQService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. namespace App\Services;
  3. use PhpAmqpLib\Connection\AMQPStreamConnection;
  4. use PhpAmqpLib\Channel\AMQPChannel;
  5. use PhpAmqpLib\Message\AMQPMessage;
  6. use PhpAmqpLib\Wire\AMQPTable;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Str;
  9. use App\Exceptions\TaskFailException;
  10. class RabbitMQService
  11. {
  12. private $connection;
  13. private $channel;
  14. private array $config;
  15. private array $queues;
  16. public function __construct()
  17. {
  18. $this->config = config('queue.connections.rabbitmq');
  19. $this->queues = config('mint.rabbitmq.queues');
  20. $this->connect();
  21. }
  22. private function connect()
  23. {
  24. $conn = $this->config;
  25. $this->connection = new AMQPStreamConnection(
  26. $conn['host'],
  27. $conn['port'],
  28. $conn['user'],
  29. $conn['password'],
  30. $conn['virtual_host']
  31. );
  32. $this->channel = $this->connection->channel();
  33. // 设置 QoS - 每次只处理一条消息
  34. $this->channel->basic_qos(null, 1, null);
  35. }
  36. public function getChannel(): AMQPChannel
  37. {
  38. return $this->channel;
  39. }
  40. public function createQueue(): array
  41. {
  42. foreach ($this->queues as $name => $queue) {
  43. $args = [];
  44. // TTL
  45. if (!empty($queue['ttl'])) {
  46. $args['x-message-ttl'] = (int) $queue['ttl'];
  47. }
  48. // max length
  49. if (!empty($queue['max_length'])) {
  50. $args['x-max-length'] = (int) $queue['max_length'];
  51. }
  52. // dead letter exchange
  53. if (!empty($queue['dead_letter_exchange'])) {
  54. $args['x-dead-letter-exchange'] = $queue['dead_letter_exchange'];
  55. }
  56. // dead letter routing key(可选但建议)
  57. if (!empty($queue['dead_letter_queue'])) {
  58. $args['x-dead-letter-routing-key'] = $queue['dead_letter_queue'];
  59. }
  60. $this->channel->queue_declare(
  61. $name, // queue 名称
  62. false, // passive:检查是否存在(false=不存在则创建)
  63. true, // durable:是否持久化(重启 RabbitMQ 后仍存在)
  64. false, // exclusive:独占模式
  65. false, // auto_delete:是否在无消费者时自动删除
  66. false, // nowait:是否不等待服务器响应(false=阻塞等待确认)
  67. new AMQPTable($args) // arguments:附加参数(TTL / DLX / max-length 等)
  68. );
  69. }
  70. return array_keys($this->queues);
  71. }
  72. public function setupQueue(string $queueName): void
  73. {
  74. $queueConfig = config("mint.rabbitmq.queues.{$queueName}");
  75. $workerArgs = [];
  76. if (isset($queueConfig['ttl'])) {
  77. $workerArgs['x-message-ttl'] = $queueConfig['ttl'];
  78. }
  79. if (isset($queueConfig['max_length'])) {
  80. $workerArgs['x-max-length'] = $queueConfig['max_length'];
  81. }
  82. // 创建死信交换机
  83. if (isset($queueConfig['dead_letter_exchange'])) {
  84. $this->channel->exchange_declare(
  85. $queueConfig['dead_letter_exchange'],
  86. 'direct',
  87. false,
  88. true,
  89. false
  90. );
  91. $dlqName = $queueConfig['dead_letter_queue'];
  92. $dlqConfig = config("mint.rabbitmq.dead_letter_queues.{$dlqName}", []);
  93. $dlqArgs = [];
  94. if (isset($dlqConfig['ttl'])) {
  95. $dlqArgs['x-message-ttl'] = $dlqConfig['ttl'];
  96. }
  97. if (isset($dlqConfig['max_length'])) {
  98. $dlqArgs['x-max-length'] = $dlqConfig['max_length'];
  99. }
  100. $dlqArguments = new AMQPTable($dlqArgs);
  101. // 创建死信队列
  102. $this->channel->queue_declare(
  103. $dlqName,
  104. false, // passive
  105. true, // durable
  106. false, // exclusive
  107. false, // auto_delete
  108. false, // nowait
  109. $dlqArguments
  110. );
  111. // 绑定死信队列到死信交换机
  112. $this->channel->queue_bind(
  113. $queueConfig['dead_letter_queue'],
  114. $queueConfig['dead_letter_exchange']
  115. );
  116. // 主队列,配置死信
  117. $workerArgs['x-dead-letter-exchange'] = $queueConfig['dead_letter_exchange'];
  118. $workerArgs['x-dead-letter-routing-key'] = $queueConfig['dead_letter_queue'];
  119. }
  120. $arguments = new AMQPTable($workerArgs);
  121. $this->channel->queue_declare(
  122. $queueName,
  123. false, // passive
  124. true, // durable
  125. false, // exclusive
  126. false, // auto_delete
  127. false, // nowait
  128. $arguments
  129. );
  130. /*
  131. // 检查队列是否存在
  132. try {
  133. $this->channel->queue_declare(
  134. $queueName,
  135. true, // passive
  136. true, // durable
  137. false, // exclusive
  138. false, // auto_delete
  139. false, // nowait
  140. $arguments
  141. );
  142. //存在,不用创建
  143. } catch (\Exception $e) {
  144. if (strpos($e->getMessage(), 'NOT_FOUND') !== false) {
  145. Log::info("Queue $queueName does not exist.");
  146. // 队列不存在,创建新队列
  147. $this->channel->queue_declare(
  148. $queueName,
  149. false, // passive
  150. true, // durable
  151. false, // exclusive
  152. false, // auto_delete
  153. false, // nowait
  154. $arguments
  155. );
  156. } else {
  157. Log::error("Error checking queue $queueName: {$e->getMessage()}");
  158. throw $e;
  159. }
  160. }
  161. */
  162. }
  163. public function publishMessage(string $queueName, array $data): string
  164. {
  165. try {
  166. $this->setupQueue($queueName);
  167. $msgId = Str::uuid();
  168. $message = new AMQPMessage(
  169. json_encode($data, JSON_UNESCAPED_UNICODE),
  170. [
  171. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  172. 'timestamp' => time(),
  173. 'message_id' => $msgId,
  174. "content_type" => 'application/json; charset=utf-8'
  175. ]
  176. );
  177. $this->channel->basic_publish($message, '', $queueName);
  178. Log::info("Message published to queue: {$queueName} msg id={$msgId}");
  179. return $msgId;
  180. } catch (\Exception $e) {
  181. Log::error("Failed to publish message to queue: {$queueName}", [
  182. 'error' => $e->getMessage(),
  183. ]);
  184. throw $e;
  185. }
  186. }
  187. public function consume(string $queueName, callable $callback, int $maxIterations = null): void
  188. {
  189. $this->setupQueue($queueName);
  190. $maxIterations = $maxIterations ?? $this->config['consumer']['max_iterations'];
  191. $iteration = 0;
  192. $consumerCallback = function (AMQPMessage $msg) use ($callback, $queueName, &$iteration) {
  193. try {
  194. $data = json_decode($msg->getBody(), true);
  195. $retryCount = $this->getRetryCount($msg);
  196. $maxRetries = $this->config['queues'][$queueName]['retry_count'];
  197. Log::info("Processing message from queue: {$queueName}", [
  198. 'data' => $data,
  199. 'retry_count' => $retryCount,
  200. 'delivery_tag' => $msg->getDeliveryTag()
  201. ]);
  202. // 执行回调处理消息
  203. $callback($data, $retryCount);
  204. // 处理成功,确认消息
  205. $msg->ack();
  206. Log::info("Message processed successfully", ['delivery_tag' => $msg->getDeliveryTag()]);
  207. } catch (TaskFailException $e) {
  208. //no need requeue
  209. Log::error("Error processing message", [
  210. 'error' => $e->getMessage(),
  211. 'delivery_tag' => $msg->getDeliveryTag()
  212. ]);
  213. $msg->nack(false, false);
  214. } catch (\Exception $e) {
  215. // 处理失败,检查重试次数
  216. if ($retryCount < $maxRetries) {
  217. // 重新入队,延迟处理
  218. $this->requeueWithDelay($msg, $queueName, $retryCount + 1);
  219. Log::warning("Message requeued for retry", [
  220. 'delivery_tag' => $msg->getDeliveryTag(),
  221. 'retry_count' => $retryCount + 1
  222. ]);
  223. } else {
  224. // 超过重试次数,拒绝消息(进入死信队列)
  225. $msg->nack(false, false);
  226. Log::error("Message rejected after max retries", [
  227. 'delivery_tag' => $msg->getDeliveryTag(),
  228. 'retry_count' => $retryCount
  229. ]);
  230. }
  231. }
  232. $iteration++;
  233. };
  234. $this->channel->basic_qos(null, 1, null);
  235. $this->channel->basic_consume($queueName, '', false, false, false, false, $consumerCallback);
  236. Log::info("Starting consumer for queue: {$queueName}", ['max_iterations' => $maxIterations]);
  237. while ($this->channel->is_consuming() && $iteration < $maxIterations) {
  238. $this->channel->wait(null, false, $this->config['consumer']['sleep_between_iterations']);
  239. }
  240. Log::info("Consumer stopped", ['iterations_processed' => $iteration]);
  241. }
  242. private function getRetryCount(AMQPMessage $msg): int
  243. {
  244. $headers = $msg->get_properties();
  245. return isset($headers['application_headers']['x-retry-count'])
  246. ? $headers['application_headers']['x-retry-count'] : 0;
  247. }
  248. private function requeueWithDelay(AMQPMessage $msg, string $queueName, int $retryCount): void
  249. {
  250. $delay = $this->config['queues'][$queueName]['retry_delay'];
  251. // 创建延迟队列
  252. $delayQueueName = "{$queueName}_delay_{$retryCount}";
  253. $arguments = new AMQPTable([
  254. 'x-message-ttl' => $delay,
  255. 'x-dead-letter-exchange' => '',
  256. 'x-dead-letter-routing-key' => $queueName,
  257. ]);
  258. $this->channel->queue_declare(
  259. $delayQueueName,
  260. false,
  261. true,
  262. false,
  263. false,
  264. false,
  265. $arguments
  266. );
  267. // 重新发布消息到延迟队列
  268. $data = json_decode($msg->getBody(), true);
  269. $newMessage = new AMQPMessage(
  270. json_encode($data),
  271. [
  272. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  273. 'application_headers' => new AMQPTable([
  274. 'x-retry-count' => $retryCount
  275. ])
  276. ]
  277. );
  278. $this->channel->basic_publish($newMessage, '', $delayQueueName);
  279. $msg->ack();
  280. }
  281. public function close(): void
  282. {
  283. if ($this->channel) {
  284. $this->channel->close();
  285. }
  286. if ($this->connection) {
  287. $this->connection->close();
  288. }
  289. }
  290. }