发送消息
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('192.168.56.100', 5672, 'root', 'root');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);
$channel->exchange_declare('topic_logs', 'topic', false, false, false);
$routing_key = 'anonymous.info';
$channel->queue_bind('hello', 'topic_logs', $routing_key);
$data = "Hello World!";
$msg = new AMQPMessage($data);
$channel->basic_publish($msg, 'topic_logs', $routing_key);
echo ' [x] Sent ', $routing_key, ':', $data, "\n";
$channel->close();
$connection->close();
接收消息
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('192.168.56.100', 5672, 'root', 'root');
$channel = $connection->channel();
$channel->exchange_declare('topic_logs', 'topic', false, false, false);
$queue_name = 'hello';
$binding_keys = ['anonymous.info'];
foreach ($binding_keys as $binding_key) {
$channel->queue_bind($queue_name, 'topic_logs', $binding_key);
}
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 ($channel->is_consuming()) {
$channel->wait();
}
$channel->close();
$connection->close();
网友评论