[toc] # RabbitMQ 简单使用 - php **扩展包:** ``` composer require php-amqplib/php-amqplib ``` ## 生产者(发送到队列) ```php <?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); $msg = new AMQPMessage('你好!'); $channel->basic_publish($msg, '', 'hello'); $channel->close(); $connection->close(); ``` ## 消费者 (消费队列) ```php <?php require_once 'vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); $callback = function(\PhpAmqpLib\\Message\\AMQPMessage $msg) { echo " [x] Received ", $msg->getBody(), "\n"; // 确认一个消息 (任务完成,从队列中移除) $msg->getChannel()->basic_ack($msg->getDeliveryTag()); // 重新放入队列 // $msg->getChannel()->basic_nack($msg->getDeliveryTag(), false, true); // 抛弃此消息 // $msg->getChannel()->basic_nack($msg->getDeliveryTag(), false, false); }; $channel->basic_consume('hello', '', false, false, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); } ``` **2021/5/25更新说明:`delivery_info`已弃用,推荐使用下面的方法替代ack确认消息。更加明确表达含义** ```php $msg->getChannel()->basic_ack($msg->getDeliveryTag()); if ($msg->getBody() === 'quit') { // 结束队列使用者 $msg->getChannel()->basic_cancel($msg->getConsumerTag()); } ``` **参考资料:** - [RabbitMQ+PHP 教程一(Hello World)](https://segmentfault.com/a/1190000011825148)