赞
踩
生产者:
/**
* 根据参数产生不同的生产者
* example:php emit_logs_direct.php info 'this is a info message'
*/
require_once dirname(__DIR__) . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
//创建RabbitMq连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
//创建信道
$channel = $connection->channel();
//创建叫direct_logs的交换器,类型为direct
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
//获取路由routing_key
$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);
//发送消息
//$msg=>消息,$exchange=》交换器,$routing_key=》路由
$channel->basic_publish($msg, 'direct_logs', $severity);
echo ' [x] Sent ', $severity, ':', $data, "\n";
//关闭信道和连接
$channel->close();
$connection->close();
消费者:
/**
* 这是一个通过路由routing_key来消费消息的实列
* example: php receive_logs_direct.php info warning
*/
require_once dirname(__DIR__) . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
//创建RabbitMq连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
//创建信道
$channel = $connection->channel();
//创建叫direct_logs的交换器,类型为direct
$channel->exchange_declare('direct_logs', 'direct', false, false, false);
//随机生成一个队列,并获取队列名称
list($queue_name, ,) = $channel->queue_declare("", false, false, true, false);
//通过参数来设定路由routing_key
$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();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。