【问题标题】:RabbitMQ - PHP / Python consumer problemsRabbitMQ - PHP / Python 消费者问题
【发布时间】:2012-06-22 20:02:56
【问题描述】:

我有一个 python 应用程序,它使用 pika 库将消息推送到 rabbitMQ 队列。

message='hola'
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(credentials=credentials, host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='myqueue')
channel.basic_publish(exchange='',routing_key='myqueue',body=message)
connection.close()

这行得通。

我需要在 php 应用程序中使用这些消息。我尝试了此页面的 AQMP 示例中提到的这个 - http://www.php.net/manual/en/class.amqpqueue.php(检查函数接收器)

$cnn = new AMQPConnection((array("host"=>"ec2-xxx-xx-xx-xxx.ap-southeast-1.compute.amazonaws.com","login"=>"guest", "password"=>"guest")));
if ($cnn->connect()) {
    echo "Established a connection to the broker";
}
else {
    echo "Cannot connect to the broker";
}

    $queue = new AMQPQueue($cnn); 
    $queue->declare('myqueue'); 
    $queue->bind('', 'myqueue'); 

$msg=$queue->get(AMQP_AUTOACK);
echo $msg->getBody();

抛出这个异常 -

Fatal error: Uncaught exception 'Exception' with message 'Error parsing parameters.' in /home/webroot/amqptest.php:12 Stack trace: #0 /home/webroot/amqptest.php(12): AMQPQueue->declare('myqueue') #1 {main} thrown in /home/webroot/amqptest.php on line 12

【问题讨论】:

  • 错误是什么时候出现的?是连接的时候吗?还是在您正在消费的部分?

标签: php python rabbitmq amqp


【解决方案1】:

这应该可行 - 但请记住,没有错误处理或任何循环来重复接收消息。不过,它确实为我成功地从代理中出列/接收了单个消息(如果再次运行空队列,则会崩溃)。

<?php

$cnn = new AMQPConnection();
$cnn->setLogin("guest");
$cnn->setPassword("guest");
$cnn->setHost("localhost");

if ($cnn->connect()) {
    echo "Established a connection to the broker\n";
}
else {
    echo "Cannot connect to the broker\n";
}

$channel = new AMQPChannel($cnn);
$queue = new AMQPQueue($channel);
$queue->setName('myqueue');

// the default / nameless) exchange does not require a binding
// as the broker declares a binding for each queue with key
// identical to the queue name. error 403 if you try yourself.
//$queue->bind('', 'myqueue');

$msg=$queue->get(AMQP_AUTOACK);

echo $msg->getBody();
echo "\n";

?>

特别注意,现在需要通过属性而不是数组来配置 AMQPConnection;您必须使用 AMQPChannel 传递给 AMQPQueue 对象;并且绑定到默认交换中的队列将不起作用/是不必要的。要查看效果,请尝试取消注释显示 $queue->bind 的行 :-)

我将这两个脚本的副本作为公共 Gist 放在 Github 上 - https://gist.github.com/2988379

【讨论】:

    【解决方案2】:

    我认为文件是错误的。您需要 AMQPChannel 来创建队列,而不是 AMQPConnection。可以找到队列的构造函数的定义:

    AMQPQueue::__construct(AMQPChannel channel)
    

    在AMQP包的源码中:amqp_queue.c

    【讨论】: