
发布/订阅,使用扇型交换机(fanout)
composer.json
### composer.json
{
"require": {
"php-amqplib/php-amqplib": ">=2.9.0"
}
}
发布端(Publish)
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
require_once __DIR__. DS . 'vendor' .DS.'autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('192.168.0.83', 5672, 'admin', 'admin');
$channel = $connection->channel();
$channel->exchange_declare('logs', 'fanout', false, false, false);
$data = implode('...', array_slice($argv, 1));
if (empty($data)) {
$data = 'hello publish,subscribe!';
}
$msg = new AMQPMessage($data);
$channel->basic_publish($msg, 'logs');
$channel->close();
$connection->close();
订阅端(Subscribe)
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
require_once __DIR__. DS . 'vendor' .DS.'autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('192.168.0.83', 5672, 'admin', 'admin');
$channel = $connection->channel();
$channel->exchange_declare('logs', 'fanout', false, false, false);
list($queue_name, ,) = $channel->queue_declare('', false, false, true, false);
$channel->queue_bind($queue_name, 'logs');
$callback = function($msg){
echo 'Subscribe:', $msg->body, PHP_EOL;
};
$channel->basic_consume($queue_name, '', false, true, false, false, $callback);
while($channel->is_consuming()){
$channel->wait();
}
$channel->close();
$connection->close();