生产者
require_once './vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'mq', 'mq123', '/');
$channel = $connection->channel();
$channel->exchange_declare('test_exchange_direct', 'direct', false, false, false);
//推送成功
$channel->set_ack_handler(
function (AMQPMessage $message) {
echo "成功: " . $message->body . PHP_EOL;
}
);
//推送失败
$channel->set_nack_handler(
function (AMQPMessage $message) {
echo "失败: " . $message->body . PHP_EOL;
}
);
$channel->confirm_select();
$channel->basic_publish(new AMQPMessage('info日志'), 'test_exchange_direct', 'info');
$channel->basic_publish(new AMQPMessage('error日志'), 'test_exchange_direct', 'error');
$channel->wait_for_pending_acks();
$channel->close();
$connection->close();
消费者
require_once './vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'mq', 'mq123', '/');
$channel = $connection->channel();
$channel->exchange_declare('test_exchange_direct', 'direct', false, false, false);
list($queue_name, ,) = $channel->queue_declare("", false, false, true, false);
$severities = array_slice($argv, 1);
foreach($severities as $severity) {
$channel->queue_bind($queue_name, 'test_exchange_direct', $severity);
}
echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";
$callback = function($msg){
echo ' [x] ',$msg->delivery_info['routing_key'], ':', $msg->body, "\n";
};
$channel->basic_consume($queue_name, '', false, true, false, false, $callback);
while(count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
结果