首页 > 解决方案 > PHP RabbitMQ - 如何将队列中的多条消息分配给 PHP 脚本中各自的变量

问题描述

到目前为止,我可以使用此脚本(send.php)将三条消息写入队列注意这是取自 RabbitMQs 教程

<?php

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

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

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

$msg1 = new AMQPMessage('Blue');             //I wanted this to be assigned to $color
$msg2 = new AMQPMessage('English');          //I wanted this to be assigned to $language
$msg3 = new AMQPMessage('Canada');           //I wanted this to be assigned to $country

$channel->basic_publish($msg1, '', 'hello');
$channel->basic_publish($msg2, '', 'hello');
$channel->basic_publish($msg3, '', 'hello');

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

$channel->close();
$connection->close();
?>

这是另一个将从 RabbitMQ (recieve.php) 接收消息的脚本注意这是取自 RabbitMQs 教程

<?php

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

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

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

echo " [*] Waiting for messages. To exit press CTRL+C\n";

$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while ($channel->is_consuming()) {
    $channel->wait();
}

$channel->close();
$connection->close();
?>

当我运行接收脚本时,输出如下所示:

[*] Waiting for messages. To exit press CTRL+C
Blue
English
Canada

我遇到的问题是将这些单独的消息放入他们自己的 PHP 变量中。我希望有这样的事情:

$color = $msg1->body;
$language = $msg2->body;
$country = $msg3->body;

我尝试进入recieve.php 文件并将$msg1->body、$msg2->body、$msg->body 添加到脚本中,但这会将所有三个消息放入一个变量中。

标签: phprabbitmq

解决方案


你可以使用队列对象,questionKid。

/* create a queue object */
$queue = new AMQPQueue($channel);

//declare the queue
$queue->declare('myqueue');

//get the messages
$messages = $queue->get(AMQP_AUTOACK);

echo $message->getBody();

归功于这篇文章。也必须有某种方式来使用基于渠道的方法。


推荐阅读