消息的流转是什么样的?

疑问:消息是发给exchange,还是直接发到queue里的?

  1. 生产者->队列->消费者

请输入图片描述

  1. 生产者->交换机->队列->消费者

请输入图片描述

实践

查看官方例子:send.php
仓库地址:https://github.com/xiaochengfu/rabbitmq-tutorials/blob/develop/php/send.php

send.php代码注释中有详细说明
<?php

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('59.110.213.203', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

$msg = new AMQPMessage('Hello World!');
$channel->basic_publish($msg, '', 'hello'); //1:msg 2:exchange 3:routing_key

echo " [x] Sent 'Hello World!'\n";

$channel->close();
$connection->close();
?>
总结
  1. exchange虽然为空字符,但是使用了rabbitmq内置的(AMQP default)
  2. 队列虽然没有用queue_bind()方式显示的绑定exchange,但内部其实是与内置的(AMQP default)交换机进行了绑定
  3. routing_key去掉或改名后收不到,是因为绑定到默认exchange时,routing_key必须和queue名称一致才有效
  4. 一个消息不能直接发给队列,是必须要经过交换机的

引用

  1. In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    官方文档:https://www.rabbitmq.com/tutorials/tutorial-one-python.html