企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
如果接收的消息routeKey很多,那我们就的一行行添加(当然你可以采用foreach循环),如果我们要对日志的来源进行再分类,比方说有register、login、mail等等,那么久需要bind很多的routeKey,大概会如下: ~~~ $queue->bind('exchange.log','register.warning'); $queue->bind('exchange.logs','register.error'); $queue->bind('exchange.logs','register.critical'); $queue->bind('exchange.logs','register.alert'); $queue->bind('exchange.logs','register.emergency'); ....... $queue->bind('exchange.log','mail.warning'); $queue->bind('exchange.logs','mail.error'); $queue->bind('exchange.logs','mail.critical'); $queue->bind('exchange.logs','mail.alert'); $queue->bind('exchange.logs','mail.emergency'); ~~~ 那么我们有没有一种办法来处理这种情况呢,这就是本章的学习的exchange中topic类型。 使用topic类型后,routKey支持模糊匹配,但仅支持以下2种写法: *(星号)可以代表一个单词 #(井号)可以代表零个或多个单词 //请务必注意是单词,此时的routeKey是使用.链接的字符串。 topic_send.php ~~~ <?php $config = [ 'host' => '127.0.0.1', 'vhost' => '/', 'port' => 5672, 'login' => 'guest', 'password' => 'guest' ]; $conn = new \AMQPConnection($config); $conn->connect(); $channel = new \AMQPChannel($conn); $channel->qos(0,0); $exchange = new \AMQPExchange($channel); $exchange->setName('exchange.all.logs'); $exchange->setType(AMQP_EX_TYPE_TOPIC); $exchange->setFlags(AMQP_DURABLE); $exchange->declareExchange(); //循环生成消息需要发布的消息 $origins = ['register','login','mail']; $levels = ['debug','info','notice','warning','error','critical','alert','emergency']; foreach ($origins as $origin) { foreach ($levels as $level) { $message = "[$origin]Message[$level]"; $routeKey = "$origin.$level"; //echo $message."======".$routeKey."\n"; $result = $exchange->publish($message, $routeKey); var_dump($result); } } ~~~ topic_receive.php ~~~ <?php $config = [ 'host' => '127.0.0.1', 'vhost' => '/', 'port' => 5672, 'login' => 'guest', 'password' => 'guest' ]; $conn = new \AMQPConnection($config); $conn->connect(); $channel = new \AMQPChannel($conn); $channel->qos(0,1); $queue = new \AMQPQueue($channel); $queue->setName("queue.all.errors"); $queue->setFlags(AMQP_DURABLE); $queue->declareQueue(); $queue->bind('exchange.all.logs','#.warning'); $queue->bind('exchange.all.logs','#.error'); $queue->bind('exchange.all.logs','#.critical'); $queue->bind('exchange.all.logs','#.alert'); $queue->bind('exchange.all.logs','#.emergency'); $queue->consume('processMessage',AMQP_AUTOACK); function processMessage($envelope, $queue) { global $i; echo "Message $i: " . $envelope->getBody() . "\n"; $i++; } ~~~