RabbitMQService.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. class RabbitMQService
  10. {
  11. private $connection;
  12. private $channel;
  13. private $config;
  14. public function __construct()
  15. {
  16. $this->config = config('queue.connections.rabbitmq');
  17. $this->connect();
  18. }
  19. private function connect()
  20. {
  21. $conn = $this->config;
  22. $this->connection = new AMQPStreamConnection(
  23. $conn['host'],
  24. $conn['port'],
  25. $conn['user'],
  26. $conn['password'],
  27. $conn['virtual_host']
  28. );
  29. $this->channel = $this->connection->channel();
  30. // 设置 QoS - 每次只处理一条消息
  31. $this->channel->basic_qos(null, 1, null);
  32. }
  33. public function getChannel(): AMQPChannel
  34. {
  35. return $this->channel;
  36. }
  37. public function setupQueue(string $queueName): void
  38. {
  39. $queueConfig = config("mint.rabbitmq.queues.{$queueName}");
  40. // 创建死信交换机
  41. if (isset($queueConfig['dead_letter_exchange'])) {
  42. $this->channel->exchange_declare(
  43. $queueConfig['dead_letter_exchange'],
  44. 'direct',
  45. false,
  46. true,
  47. false
  48. );
  49. $dlqName = $queueConfig['dead_letter_queue'];
  50. $dlqConfig = config("mint.rabbitmq.dead_letter_queues.{$dlqName}", []);
  51. $dlqArgs = [];
  52. if (isset($dlqConfig['ttl'])) {
  53. $dlqArgs['x-message-ttl'] = $dlqConfig['ttl'];
  54. }
  55. if (isset($dlqConfig['max_length'])) {
  56. $dlqArgs['x-max-length'] = $dlqConfig['max_length'];
  57. }
  58. $dlqArguments = new AMQPTable($dlqArgs);
  59. // 创建死信队列
  60. $this->channel->queue_declare(
  61. $dlqName,
  62. false, // passive
  63. true, // durable
  64. false, // exclusive
  65. false, // auto_delete
  66. false, // nowait
  67. $dlqArguments
  68. );
  69. // 绑定死信队列到死信交换机
  70. $this->channel->queue_bind(
  71. $queueConfig['dead_letter_queue'],
  72. $queueConfig['dead_letter_exchange']
  73. );
  74. // 创建主队列,配置死信
  75. $arguments = new AMQPTable([
  76. 'x-dead-letter-exchange' => $queueConfig['dead_letter_exchange'],
  77. 'x-dead-letter-routing-key' => $queueConfig['dead_letter_queue'], // 死信路由键
  78. ]);
  79. } else {
  80. $workerArgs = [];
  81. if (isset($queueConfig['ttl'])) {
  82. $workerArgs['x-message-ttl'] = $queueConfig['ttl'];
  83. }
  84. if (isset($queueConfig['max_length'])) {
  85. $workerArgs['x-max-length'] = $queueConfig['max_length'];
  86. }
  87. $arguments = new AMQPTable($workerArgs);
  88. }
  89. $this->channel->queue_declare(
  90. $queueName,
  91. false, // passive
  92. true, // durable
  93. false, // exclusive
  94. false, // auto_delete
  95. false, // nowait
  96. $arguments
  97. );
  98. }
  99. public function publishMessage(string $queueName, array $data): bool
  100. {
  101. try {
  102. $this->setupQueue($queueName);
  103. $message = new AMQPMessage(
  104. json_encode($data, JSON_UNESCAPED_UNICODE),
  105. [
  106. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  107. 'timestamp' => time(),
  108. 'message_id' => Str::uuid(),
  109. "content_type" => 'application/json; charset=utf-8'
  110. ]
  111. );
  112. $this->channel->basic_publish($message, '', $queueName);
  113. Log::info("Message published to queue: {$queueName}", $data);
  114. return true;
  115. } catch (\Exception $e) {
  116. Log::error("Failed to publish message to queue: {$queueName}", [
  117. 'error' => $e->getMessage(),
  118. 'data' => $data
  119. ]);
  120. return false;
  121. }
  122. }
  123. public function consume(string $queueName, callable $callback, int $maxIterations = null): void
  124. {
  125. $this->setupQueue($queueName);
  126. $maxIterations = $maxIterations ?? $this->config['consumer']['max_iterations'];
  127. $iteration = 0;
  128. $consumerCallback = function (AMQPMessage $msg) use ($callback, $queueName, &$iteration) {
  129. try {
  130. $data = json_decode($msg->getBody(), true);
  131. $retryCount = $this->getRetryCount($msg);
  132. $maxRetries = $this->config['queues'][$queueName]['retry_count'];
  133. Log::info("Processing message from queue: {$queueName}", [
  134. 'data' => $data,
  135. 'retry_count' => $retryCount,
  136. 'delivery_tag' => $msg->getDeliveryTag()
  137. ]);
  138. // 执行回调处理消息
  139. $result = $callback($data, $retryCount);
  140. if ($result === true) {
  141. // 处理成功,确认消息
  142. $msg->ack();
  143. Log::info("Message processed successfully", ['delivery_tag' => $msg->getDeliveryTag()]);
  144. } else {
  145. // 处理失败,检查重试次数
  146. if ($retryCount < $maxRetries) {
  147. // 重新入队,延迟处理
  148. $this->requeueWithDelay($msg, $queueName, $retryCount + 1);
  149. Log::warning("Message requeued for retry", [
  150. 'delivery_tag' => $msg->getDeliveryTag(),
  151. 'retry_count' => $retryCount + 1
  152. ]);
  153. } else {
  154. // 超过重试次数,拒绝消息(进入死信队列)
  155. $msg->nack(false, false);
  156. Log::error("Message rejected after max retries", [
  157. 'delivery_tag' => $msg->getDeliveryTag(),
  158. 'retry_count' => $retryCount
  159. ]);
  160. }
  161. }
  162. } catch (\Exception $e) {
  163. Log::error("Error processing message", [
  164. 'error' => $e->getMessage(),
  165. 'delivery_tag' => $msg->getDeliveryTag()
  166. ]);
  167. $msg->nack(false, false);
  168. }
  169. $iteration++;
  170. };
  171. $this->channel->basic_qos(null, 1, null);
  172. $this->channel->basic_consume($queueName, '', false, false, false, false, $consumerCallback);
  173. Log::info("Starting consumer for queue: {$queueName}", ['max_iterations' => $maxIterations]);
  174. while ($this->channel->is_consuming() && $iteration < $maxIterations) {
  175. $this->channel->wait(null, false, $this->config['consumer']['sleep_between_iterations']);
  176. }
  177. Log::info("Consumer stopped", ['iterations_processed' => $iteration]);
  178. }
  179. private function getRetryCount(AMQPMessage $msg): int
  180. {
  181. $headers = $msg->get_properties();
  182. return isset($headers['application_headers']['x-retry-count'])
  183. ? $headers['application_headers']['x-retry-count'] : 0;
  184. }
  185. private function requeueWithDelay(AMQPMessage $msg, string $queueName, int $retryCount): void
  186. {
  187. $delay = $this->config['queues'][$queueName]['retry_delay'];
  188. // 创建延迟队列
  189. $delayQueueName = "{$queueName}_delay_{$retryCount}";
  190. $arguments = new AMQPTable([
  191. 'x-message-ttl' => $delay,
  192. 'x-dead-letter-exchange' => '',
  193. 'x-dead-letter-routing-key' => $queueName,
  194. ]);
  195. $this->channel->queue_declare(
  196. $delayQueueName,
  197. false,
  198. true,
  199. false,
  200. false,
  201. false,
  202. $arguments
  203. );
  204. // 重新发布消息到延迟队列
  205. $data = json_decode($msg->getBody(), true);
  206. $newMessage = new AMQPMessage(
  207. json_encode($data),
  208. [
  209. 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
  210. 'application_headers' => new AMQPTable([
  211. 'x-retry-count' => $retryCount
  212. ])
  213. ]
  214. );
  215. $this->channel->basic_publish($newMessage, '', $delayQueueName);
  216. $msg->ack();
  217. }
  218. public function close(): void
  219. {
  220. if ($this->channel) {
  221. $this->channel->close();
  222. }
  223. if ($this->connection) {
  224. $this->connection->close();
  225. }
  226. }
  227. }