要在PHP中使用AMQP實現消息隊列,首先需要安裝一個AMQP擴展,如php-amqplib/php-amqplib
。以下是一個簡單的示例,展示了如何使用AMQP實現生產者(發送者)和消費者(接收者)之間的通信。
composer require php-amqplib/php-amqplib
<?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);
$message = new AMQPMessage('Hello World!');
$channel->basic_publish($message, '', 'hello');
echo " [x] Sent 'Hello World!'\n";
$channel->close();
$connection->close();
<?php
require_once __DIR__ . '/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);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
echo " [x] Received ", $msg->body, "\n";
};
$channel->basic_consume('hello', '', false, true, false, false, $callback);
while ($channel->is_consuming()) {
$channel->wait();
}
$channel->close();
$connection->close();
php sender.php
php receiver.php
在這個例子中,生產者將發送一條消息到名為hello
的隊列,而消費者將從該隊列接收并處理消息。這就是如何使用AMQP實現PHP中的消息隊列。