建立一个交换机 tpc 并且绑定了各自的路由到 Q1 Q2
<?php require_once "./vendor/autoload.php"; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; $conf = [ ‘host‘ => ‘192.168.33.50‘, ‘port‘ => 5672, ‘user‘ => ‘admin‘, ‘pwd‘ => ‘password‘, ‘vhost‘ => ‘/‘, ]; $exchangeName = ‘tpc‘; //交换机名 //$queueName = ‘ttt‘; //队列名称 $routingKey = ‘lazy.a.b‘; //路由关键字(也可以省略) $conn = new AMQPStreamConnection( //建立生产者与mq之间的连接 $conf[‘host‘], $conf[‘port‘], $conf[‘user‘], $conf[‘pwd‘], $conf[‘vhost‘] ); $channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道 $channel->exchange_declare($exchangeName, ‘topic‘, false, true, false); //声明初始化交换机 //$channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列 //$channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字 $msgBody = json_encode(["name" => "iGoo", "age" => 22]); $msg = new AMQPMessage($msgBody, [‘content_type‘ => ‘text/plain‘, ‘delivery_mode‘ => 2]); //生成消息 $r = $channel->basic_publish($msg, $exchangeName, $routingKey); //推送消息到某个交换机 $channel->close(); $conn->close();
通过代码生产消息 时候,
$routingKey = ‘lazy.a.b‘; //路由关键字(也可以省略)
Q2 会收到消息
$routingKey = ‘lazy.a‘; //路由关键字(也可以省略)
Q2也会收到消息
因为#号会匹配多个 比如 lazy.a lazy.b lazy.a.b.c
$routingKey = ‘a.orange.b‘; //路由关键字(也可以省略)
Q1会收到消息 因为只匹配到orange 前面一个后面一个
$routingKey = ‘a.orange.b.c‘; //路由关键字(也可以省略)
没有队列收到
$routingKey = ‘a.orange.rabbit‘; //路由关键字(也可以省略)
两个都匹配到, 匹配到rabbit和 中间的orange
原文:https://www.cnblogs.com/brady-wang/p/13543473.html