php - 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 添加到脚本中,但这会将所有三个消息放入一个变量中。
解决方案
你可以使用队列对象,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();
归功于这篇文章。也必须有某种方式来使用基于渠道的方法。
推荐阅读
- python - 使用 Pandas 根据多个标准选择数据
- javascript - 如何强制反应不重新渲染孩子,只是接收状态变化?
- c# - 如何在锁定屏幕的背景下运行蓝牙 Le 扫描
- sql - 嵌套计数
- webpack - 如何在 Nativescript webpack 的应用程序目录中包含 xml 文件
- sql - 单视图SQL SSAS Cube,处理Cube时找不到属性键?
- django - 使用 Django,如何使用查询集计算可用货架空间的数量?
- javascript - 在 Internet Explorer 中将 ServiceWorker 与 Blob 一起使用时本地文件出错(仅限)
- wso2 - WSO2 VFS 并行处理
- highcharts - 在系列和标签之间带有连接器的 Highcharts 折线图