官方示例地址
使用方法:打开2个shell窗口,一个运行php emit_log_direct.php info "test message"
,一个运行php receive_logs_direct.php info
,只接受指定key的信息
<?php
/**
* 生产者
* emit_log_direct.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->exchange_declare('direct_logs', 'direct', false, false, false);
// 输入参数一
$severity = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'info';
// 输入参数二
$data = implode(' ', array_slice($argv, 2));
if (empty($data)) {
$data = "Hello World!";
}
// 创建消息
$msg = new AMQPMessage($data);
// 发送消息: 发送到指定交互机direct_logs, 并且匹配定义的severity
$channel->basic_publish($msg, 'direct_logs', $severity);
// 提示文字
echo ' [x] Sent ', $severity, ':', $data, "\n";
// 关闭连接
$channel->close();
$connection->close();
?>
<?php
/**
* 消费者
* receive_logs_direct.php
*/
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
// 创建连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
// 声明交换机和使用交互机
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
// 使用临时队列: 将queue_declare第一参数设置为空字符串
list($queue_name, ,) = $channel->queue_declare("", false, false, true, false);
// 消费者接收的参数
$severities = array_slice($argv, 1);
if (empty($severities)) {
file_put_contents('php://stderr', "Usage: $argv[0] [info] [warning] [error]\n");
exit(1);
}
// 批量绑定路由key
foreach ($severities as $severity) {
$channel->queue_bind($queue_name, 'direct_logs', $severity);
}
// 提示文字
echo " [*] Waiting for logs. To exit press CTRL+C\n";
// 回调函数: 处理生产者传递数据的地方
$callback = function ($msg) {
echo ' [x] ', $msg->delivery_info['routing_key'], ':', $msg->body, "\n";
};
// 接受队列传递数据, 并交给回调函数callback处理
$channel->basic_consume($queue_name, '', false, true, false, false, $callback);
// 内存常驻
while ($channel->is_consuming()) {
$channel->wait();
}
// 关闭连接
$channel->close();
$connection->close();
?>