PHP RabbitMQ-如何在PHP脚本中将队列中的多个消息分配给它们自己的单个变量



到目前为止,我可以使用此脚本(send.php(向队列写入三条消息注意,这是从RabbitMQ教程中获得的

<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLibConnectionAMQPStreamConnection;
use PhpAmqpLibMessageAMQPMessage;
$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 PhpAmqpLibConnectionAMQPStreamConnection;
$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+Cn";
$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;

我已经尝试进入receive.php文件并添加$msg1->正文,$msg2->正文,$msg->body,但这将把所有三条消息放在一个变量中。

您可以使用队列对象,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();

这篇文章值得称赞。也必须有一些方法来使用基于渠道的方法。

最新更新