設計一個基于AMQP的PHP應用架構需要考慮多個方面,包括消息隊列的配置、生產者和消費者的實現、錯誤處理、監控和日志記錄等。以下是一個基本的架構設計示例:
pecl install amqp
安裝PHP的AMQP擴展。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, true, false, false);
function sendMessage($channel, $msg) {
$msg = new AMQPMessage($msg);
$channel->basic_publish($msg, '', 'hello');
echo " [x] Sent 'Hello World!'\n";
}
sendMessage($channel, 'Hello World!');
function callback($msg) {
echo " [x] Received ", $msg->body, "\n";
}
$channel->basic_consume('hello', '', false, true, false, false, callback);
while ($channel->is_consuming()) {
$channel->wait();
}
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('AMQP');
$log->pushHandler(new StreamHandler('php://stdout', Logger::INFO));
$log->info('Connected to RabbitMQ');
以下是一個完整的示例代碼,展示了如何連接到RabbitMQ、聲明隊列、發送和接收消息:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$log = new Logger('AMQP');
$log->pushHandler(new StreamHandler('php://stdout', Logger::INFO));
$log->info('Connected to RabbitMQ');
$channel->queue_declare('hello', false, true, false, false);
function sendMessage($channel, $msg) {
$msg = new AMQPMessage($msg);
$channel->basic_publish($msg, '', 'hello');
echo " [x] Sent 'Hello World!'\n";
}
sendMessage($channel, 'Hello World!');
function callback($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();
這個示例展示了如何使用AMQP進行基本的消息隊列操作。根據實際需求,你可以進一步擴展和優化這個架構。