在普通路由模式基础上,指定type=direct ,生产者发消息的时候需要指定路由名称,使得消费者能够只订阅消息的一个字集。例如,我们只需要把严重的错误日志信息写入日志文件(存储到磁盘),但同时仍然把所有的日志信息输出到控制台中。
发布者(emit_log_direct.php):
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', '123456');
$channel = $connection->channel();
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
// 定义错误等级
$severities = [
'info',
'notice',
'warning',
'error',
];
$data = "Hello World!";
foreach ($severities as $i => $severity) {
$msg[$i] = new AMQPMessage($data . 'level:' . $severity);
$channel->basic_publish($msg[$i], 'direct_logs', $severity);
echo " [x] Sent ",$severity,':',$data," \n";
}
$channel->close();
$connection->close();
生产者(receive_log_direct.php):
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', '123456');
$channel = $connection->channel();
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
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);
}
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";
};
$channel->basic_consume($queue_name, '', false, true, false, false, $callback);
while(count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
测试:
1) 保存error 和 warning 级别的错误日志
php receive_log_direct.php warning error > logs_from_rabbit.log
2)将info 和 notice 输出屏幕
php receive_log_direct.php info notice
3 ) 触发消息发送程序
php emit_log_direct.php error
注释:
1)php预定义变量:$argv — 传递给脚本的参数数组
第一个参数总是当前脚本的文件名,因此 $argv[0] 就是脚本文件名。
https://www.php.net/manual/zh/reserved.variables.argv.php