# 使用pecl命令安裝$ pecl install amqp
# 使用composer安裝$ composer require php-amqplib/php-amqplib
require_once __DIR__ . '/vendor/autoload.php'; $connection = new PhpAmqpLib\Connection\AMQPStreamConnection( 'localhost', 5672, 'guest', 'guest' ); $channel = $connection->channel();
$queueName = 'my_queue'; // 隊列名稱$channel->queue_declare($queueName, false, true, false, false);
$msg = new PhpAmqpLib\Message\AMQPMessage('Hello RabbitMQ!'); $channel->basic_publish($msg, '', $queueName);
$callback = function($msg) { echo 'Received message: ' . $msg->body . "\n"; $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']); }; $channel->basic_consume($queueName, '', false, true, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); }
在此代碼中,我們創建了一個回調函數來接收和處理消息。處理完消息後,通過basic_ack方法來確認消息已被成功處理,這樣即使消費者發生故障,消息也不會丟失。
$channel->close(); $connection->close();