💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
发布 / 订阅模式可以理解为广播模式:即exchange会将消息转发到所有绑定到这个exchange的队列上。针对这种广播模式,RabbitMQ增加了exchange Type的选项 AMQP_EX_TYPE_FANOUT,这种类型在发送消息,queue bind时,都将忽略route key,也就是说不需要设置 route key。 应用的场景,比方说用户注册(注销,更改姓名等)新浪,同时需要开通微博、博客、邮箱等等,如果不采用队列,按照常规的线性处理,可能注册用户会特别的慢,因为在注册的时候,需要调各种其他服务器接口,如果服务很多的话,可能客户端就超时了。如果采用普通的队列,可能在处理上也会特别的慢(不是最佳方案)。如果采用订阅模式,则是最优的选择。 ~~~ fanoutsend.php <?php $exchangeName = 'logs'; $message = empty($argv[1]) ? 'info:Hello World!' : ' '.$argv[1]; $connection = new AMQPConnection(array('host' => '127.0.0.1', 'port' => '5672', 'vhost' => '/', 'login' => 'guest', 'password' => 'guest')); $connection->connect() or die("Cannot connect to the broker!\n"); $channel = new AMQPChannel($connection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $exchange->setType(AMQP_EX_TYPE_FANOUT); $exchange->declare(); $exchange->publish($message, ''); var_dump("[x] Sent $message"); $connection->disconnect(); fanoutreceive.php <?php $exchangeName = 'logs'; $connection = new AMQPConnection(array('host' => '127.0.0.1', 'port' => '5672', 'vhost' => '/', 'login' => 'guest', 'password' => 'guest')); $connection->connect() or die("Cannot connect to the broker!\n"); $channel = new AMQPChannel($connection); $exchange = new AMQPExchange($channel); $exchange->setName($exchangeName); $exchange->setType(AMQP_EX_TYPE_FANOUT); $exchange->declare(); $queue = new AMQPQueue($channel); $queue->setFlags(AMQP_EXCLUSIVE); $queue->declare(); $queue->bind($exchangeName, ''); var_dump('[*] Waiting for messages. To exit press CTRL+C'); while (TRUE) { $queue->consume('callback'); } $connection->disconnect(); function callback($envelope, $queue) { $msg = $envelope->getBody(); var_dump(" [x] Received:" . $msg); $queue->nack($envelope->getDeliveryTag()); } fanoutreceive.php 和 fanoutreceive1.php同时能收到订阅的消息 ~~~