怎么安装rabbitmq请查看之前课程,如果已经安装,请略过此步。
mkdir vendor
cd vendor
composer require php-amqplib/php-amqplib
cd ../
mkdir topic
cd topic
touch publish.php
channel();
$channel->exchange_declare($exc_name,'topic',false,false,false);
$data = 'this is '.$routing_key.' message';
$msg = new AMQPMessage($data,['delivery_mode'=>AMQPMEssage::DELIVERY_MODE_PERSISTENT]);
$channel->basic_publish($msg,$exc_name,$routing_key);
$channel->close();
$connection->close();
touch all.php
touch user.php
touch warn.php
vi all.php
channel();
$channel->exchange_declare($exc_name,'topic',false,false,false);
list($queue_name,,) = $channel->queue_declare('',false,false,true,false);
$channel->queue_bind($queue_name,$exc_name,$routing_key);
$callback = function($msg){
echo 'received ' ,$msg->body,"\n";
$msg->ack();
};
$channel->basic_qos(null,1,null);
$channel->basic_consume($queue_name,'',false,false,false,false,$callback);
while($channel->is_open()){
$channel->wait();
}
$channel->close();
$connection->close();
vi user.php
channel();
$channel->exchange_declare($exc_name,'topic',false,false,false);
list($queue_name,,) = $channel->queue_declare('',false,false,true,false);
$channel->queue_bind($queue_name,$exc_name,$routing_key);
$callback = function($msg){
echo 'received ' ,$msg->body,"\n";
$msg->ack();
};
$channel->basic_qos(null,1,null);
$channel->basic_consume($queue_name,'',false,false,false,false,$callback);
while($channel->is_open()){
$channel->wait();
}
$channel->close();
$connection->close();
vi warn.php
channel();
$channel->exchange_declare($exc_name,'topic',false,false,false);
list($queue_name,,) = $channel->queue_declare('',false,false,true,false);
$channel->queue_bind($queue_name,$exc_name,$routing_key);
$callback = function($msg){
echo 'received ' ,$msg->body,"\n";
$msg->ack();
};
$channel->basic_qos(null,1,null);
$channel->basic_consume($queue_name,'',false,false,false,false,$callback);
while($channel->is_open()){
$channel->wait();
}
$channel->close();
$connection->close();
php all.php
php user.php
php warn.php
php publish.php
此时你会发现只有warn.php对应的消费者及all.php都有数据,如果你把publish.php生产者里面的$routing_key对应的值改成user.goods,你会发现user.php及all.php对应的消费者都有数据。这就是rabbitmq topic工作模式硬实力